summaryrefslogtreecommitdiff
path: root/usr.sbin/nsd
diff options
context:
space:
mode:
authorStuart Henderson <sthen@cvs.openbsd.org>2013-02-18 10:17:45 +0000
committerStuart Henderson <sthen@cvs.openbsd.org>2013-02-18 10:17:45 +0000
commitb0c1602e0968a3f81c378c5c32d38eaa302845c5 (patch)
tree681d1af94867e3a02955413fdb7530200a3e03f3 /usr.sbin/nsd
parent15717be0c7572c6b742ee20d546772cee2d234ee (diff)
Update to NSD 3.2.15, ok brad@ phessler@ deraadt@ also tested by okan@
Diffstat (limited to 'usr.sbin/nsd')
-rw-r--r--usr.sbin/nsd/configlexer.lex4
-rw-r--r--usr.sbin/nsd/dbcreate.c2
-rw-r--r--usr.sbin/nsd/difffile.c15
-rw-r--r--usr.sbin/nsd/ipc.c16
-rw-r--r--usr.sbin/nsd/lookup3.c1011
-rw-r--r--usr.sbin/nsd/lookup3.h71
-rw-r--r--usr.sbin/nsd/nsd.conf.sample.in29
-rw-r--r--usr.sbin/nsd/nsd.h1
-rw-r--r--usr.sbin/nsd/nsec3.h2
-rw-r--r--usr.sbin/nsd/options.c11
-rw-r--r--usr.sbin/nsd/options.h12
-rw-r--r--usr.sbin/nsd/packet.c2
-rw-r--r--usr.sbin/nsd/query.h5
-rw-r--r--usr.sbin/nsd/rrl.c463
-rw-r--r--usr.sbin/nsd/rrl.h71
-rw-r--r--usr.sbin/nsd/tsig-openssl.c15
-rw-r--r--usr.sbin/nsd/tsig.c27
-rw-r--r--usr.sbin/nsd/tsig.h5
-rw-r--r--usr.sbin/nsd/xfrd.c15
19 files changed, 1722 insertions, 55 deletions
diff --git a/usr.sbin/nsd/configlexer.lex b/usr.sbin/nsd/configlexer.lex
index ae844ee3166..d98a4ae0acc 100644
--- a/usr.sbin/nsd/configlexer.lex
+++ b/usr.sbin/nsd/configlexer.lex
@@ -138,6 +138,10 @@ algorithm{COLON} { LEXOUT(("v(%s) ", yytext)); return VAR_ALGORITHM;}
secret{COLON} { LEXOUT(("v(%s) ", yytext)); return VAR_SECRET;}
AXFR { LEXOUT(("v(%s) ", yytext)); return VAR_AXFR;}
UDP { LEXOUT(("v(%s) ", yytext)); return VAR_UDP;}
+rrl-size{COLON} { LEXOUT(("v(%s) ", yytext)); return VAR_RRL_SIZE;}
+rrl-ratelimit{COLON} { LEXOUT(("v(%s) ", yytext)); return VAR_RRL_RATELIMIT;}
+rrl-whitelist-ratelimit{COLON} { LEXOUT(("v(%s) ", yytext)); return VAR_RRL_WHITELIST_RATELIMIT;}
+rrl-whitelist{COLON} { LEXOUT(("v(%s) ", yytext)); return VAR_RRL_WHITELIST;}
{NEWLINE} { LEXOUT(("NL\n")); cfg_parser->line++;}
/* Quoted strings. Strip leading and ending quotes */
diff --git a/usr.sbin/nsd/dbcreate.c b/usr.sbin/nsd/dbcreate.c
index 4380e91a48d..f193792debb 100644
--- a/usr.sbin/nsd/dbcreate.c
+++ b/usr.sbin/nsd/dbcreate.c
@@ -7,7 +7,7 @@
*
*/
-#include <config.h>
+#include "config.h"
#include <sys/types.h>
#include <errno.h>
diff --git a/usr.sbin/nsd/difffile.c b/usr.sbin/nsd/difffile.c
index aed2ad10aa0..3d87fce5201 100644
--- a/usr.sbin/nsd/difffile.c
+++ b/usr.sbin/nsd/difffile.c
@@ -7,7 +7,7 @@
*
*/
-#include <config.h>
+#include "config.h"
#include <assert.h>
#include <string.h>
#include <unistd.h>
@@ -85,7 +85,6 @@ diff_write_packet(const char* zone, uint32_t new_serial, uint16_t id,
log_msg(LOG_ERR, "could not write to file %s: %s",
filename, strerror(errno));
}
- fflush(df);
fclose(df);
}
@@ -439,8 +438,8 @@ delete_RR(namedb_type* db, const dname_type* dname,
}
rrnum = find_rr_num(rrset, type, klass, rdatas, rdata_num);
if(rrnum == -1) {
- log_msg(LOG_WARNING, "diff: RR %s does not exist",
- dname_to_string(dname,0));
+ log_msg(LOG_WARNING, "diff: RR <%s, %s> does not exist",
+ dname_to_string(dname,0), rrtype_to_string(type));
return 1; /* not fatal error */
}
#ifdef NSEC3
@@ -532,8 +531,8 @@ add_RR(namedb_type* db, const dname_type* dname,
}
rrnum = find_rr_num(rrset, type, klass, rdatas, rdata_num);
if(rrnum != -1) {
- DEBUG(DEBUG_XFRD, 2, (LOG_ERR, "diff: RR %s already exists",
- dname_to_string(dname,0)));
+ DEBUG(DEBUG_XFRD, 2, (LOG_ERR, "diff: RR <%s, %s> already exists",
+ dname_to_string(dname,0), rrtype_to_string(type)));
/* ignore already existing RR: lenient accepting of messages */
return 1;
}
@@ -1294,8 +1293,6 @@ read_sure_part(namedb_type* db, FILE *in, nsd_options_t* opt,
int is_axfr=0, delete_mode=0, rr_count=0;
off_t resume_pos;
- DEBUG(DEBUG_XFRD,1, (LOG_INFO, "processing xfr: %s", log_buf));
-
#ifdef NSEC3
#ifndef FULL_PREHASH
struct region *region;
@@ -1329,6 +1326,8 @@ read_sure_part(namedb_type* db, FILE *in, nsd_options_t* opt,
#endif /* !FULL_PREHASH */
#endif /* NSEC3 */
+ DEBUG(DEBUG_XFRD,1, (LOG_INFO, "processing xfr: %s", log_buf));
+
resume_pos = ftello(in);
if(resume_pos == -1) {
log_msg(LOG_INFO, "could not ftello: %s.", strerror(errno));
diff --git a/usr.sbin/nsd/ipc.c b/usr.sbin/nsd/ipc.c
index b2911e39f6b..a380815b50d 100644
--- a/usr.sbin/nsd/ipc.c
+++ b/usr.sbin/nsd/ipc.c
@@ -72,6 +72,18 @@ handle_xfrd_zone_state(struct nsd* nsd, buffer_type* packet)
return zone;
}
+static void
+ipc_child_quit(struct nsd* nsd)
+{
+ /* call shutdown and quit routines */
+ nsd->mode = NSD_QUIT;
+#ifdef BIND8_STATS
+ bind8_stats(nsd);
+#endif /* BIND8_STATS */
+ server_shutdown(nsd);
+ exit(0);
+}
+
void
child_handle_parent_command(netio_type *ATTR_UNUSED(netio),
netio_handler_type *handler,
@@ -117,9 +129,11 @@ child_handle_parent_command(netio_type *ATTR_UNUSED(netio),
switch (mode) {
case NSD_STATS:
- case NSD_QUIT:
data->nsd->mode = mode;
break;
+ case NSD_QUIT:
+ ipc_child_quit(data->nsd);
+ break;
case NSD_ZONE_STATE:
data->conn->is_reading = 1;
data->conn->total_bytes = 0;
diff --git a/usr.sbin/nsd/lookup3.c b/usr.sbin/nsd/lookup3.c
new file mode 100644
index 00000000000..6fedd4d69d1
--- /dev/null
+++ b/usr.sbin/nsd/lookup3.c
@@ -0,0 +1,1011 @@
+/*
+ January 2012(Wouter) added randomised initial value, fallout from 28c3.
+ March 2007(Wouter) adapted from lookup3.c original, add config.h include.
+ added #ifdef VALGRIND to remove 298,384,660 'unused variable k8' warnings.
+ added include of lookup3.h to check definitions match declarations.
+ removed include of stdint - config.h takes care of platform independence.
+ url http://burtleburtle.net/bob/hash/index.html.
+*/
+/*
+-------------------------------------------------------------------------------
+lookup3.c, by Bob Jenkins, May 2006, Public Domain.
+
+These are functions for producing 32-bit hashes for hash table lookup.
+hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final()
+are externally useful functions. Routines to test the hash are included
+if SELF_TEST is defined. You can use this free for any purpose. It's in
+the public domain. It has no warranty.
+
+You probably want to use hashlittle(). hashlittle() and hashbig()
+hash byte arrays. hashlittle() is is faster than hashbig() on
+little-endian machines. Intel and AMD are little-endian machines.
+On second thought, you probably want hashlittle2(), which is identical to
+hashlittle() except it returns two 32-bit hashes for the price of one.
+You could implement hashbig2() if you wanted but I haven't bothered here.
+
+If you want to find a hash of, say, exactly 7 integers, do
+ a = i1; b = i2; c = i3;
+ mix(a,b,c);
+ a += i4; b += i5; c += i6;
+ mix(a,b,c);
+ a += i7;
+ final(a,b,c);
+then use c as the hash value. If you have a variable length array of
+4-byte integers to hash, use hashword(). If you have a byte array (like
+a character string), use hashlittle(). If you have several byte arrays, or
+a mix of things, see the comments above hashlittle().
+
+Why is this so big? I read 12 bytes at a time into 3 4-byte integers,
+then mix those integers. This is fast (you can do a lot more thorough
+mixing with 12*3 instructions on 3 integers than you can with 3 instructions
+on 1 byte), but shoehorning those bytes into integers efficiently is messy.
+-------------------------------------------------------------------------------
+*/
+/*#define SELF_TEST 1*/
+
+#include "config.h"
+#include "lookup3.h"
+#include <stdio.h> /* defines printf for tests */
+#include <time.h> /* defines time_t for timings in the test */
+/*#include <stdint.h> defines uint32_t etc (from config.h) */
+#include <sys/param.h> /* attempt to define endianness */
+#ifdef linux
+# include <endian.h> /* attempt to define endianness */
+#endif
+
+/* random initial value */
+static uint32_t raninit = 0xdeadbeef;
+
+void
+hash_set_raninit(uint32_t v)
+{
+ raninit = v;
+}
+
+/*
+ * My best guess at if you are big-endian or little-endian. This may
+ * need adjustment.
+ */
+#if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
+ __BYTE_ORDER == __LITTLE_ENDIAN) || \
+ (defined(i386) || defined(__i386__) || defined(__i486__) || \
+ defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL))
+# define HASH_LITTLE_ENDIAN 1
+# define HASH_BIG_ENDIAN 0
+#elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \
+ __BYTE_ORDER == __BIG_ENDIAN) || \
+ (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel))
+# define HASH_LITTLE_ENDIAN 0
+# define HASH_BIG_ENDIAN 1
+#else
+# define HASH_LITTLE_ENDIAN 0
+# define HASH_BIG_ENDIAN 0
+#endif
+
+#define hashsize(n) ((uint32_t)1<<(n))
+#define hashmask(n) (hashsize(n)-1)
+#define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
+
+/*
+-------------------------------------------------------------------------------
+mix -- mix 3 32-bit values reversibly.
+
+This is reversible, so any information in (a,b,c) before mix() is
+still in (a,b,c) after mix().
+
+If four pairs of (a,b,c) inputs are run through mix(), or through
+mix() in reverse, there are at least 32 bits of the output that
+are sometimes the same for one pair and different for another pair.
+This was tested for:
+* pairs that differed by one bit, by two bits, in any combination
+ of top bits of (a,b,c), or in any combination of bottom bits of
+ (a,b,c).
+* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+ is commonly produced by subtraction) look like a single 1-bit
+ difference.
+* the base values were pseudorandom, all zero but one bit set, or
+ all zero plus a counter that starts at zero.
+
+Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that
+satisfy this are
+ 4 6 8 16 19 4
+ 9 15 3 18 27 15
+ 14 9 3 7 17 3
+Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing
+for "differ" defined as + with a one-bit base and a two-bit delta. I
+used http://burtleburtle.net/bob/hash/avalanche.html to choose
+the operations, constants, and arrangements of the variables.
+
+This does not achieve avalanche. There are input bits of (a,b,c)
+that fail to affect some output bits of (a,b,c), especially of a. The
+most thoroughly mixed value is c, but it doesn't really even achieve
+avalanche in c.
+
+This allows some parallelism. Read-after-writes are good at doubling
+the number of bits affected, so the goal of mixing pulls in the opposite
+direction as the goal of parallelism. I did what I could. Rotates
+seem to cost as much as shifts on every machine I could lay my hands
+on, and rotates are much kinder to the top and bottom bits, so I used
+rotates.
+-------------------------------------------------------------------------------
+*/
+#define mix(a,b,c) \
+{ \
+ a -= c; a ^= rot(c, 4); c += b; \
+ b -= a; b ^= rot(a, 6); a += c; \
+ c -= b; c ^= rot(b, 8); b += a; \
+ a -= c; a ^= rot(c,16); c += b; \
+ b -= a; b ^= rot(a,19); a += c; \
+ c -= b; c ^= rot(b, 4); b += a; \
+}
+
+/*
+-------------------------------------------------------------------------------
+final -- final mixing of 3 32-bit values (a,b,c) into c
+
+Pairs of (a,b,c) values differing in only a few bits will usually
+produce values of c that look totally different. This was tested for
+* pairs that differed by one bit, by two bits, in any combination
+ of top bits of (a,b,c), or in any combination of bottom bits of
+ (a,b,c).
+* "differ" is defined as +, -, ^, or ~^. For + and -, I transformed
+ the output delta to a Gray code (a^(a>>1)) so a string of 1's (as
+ is commonly produced by subtraction) look like a single 1-bit
+ difference.
+* the base values were pseudorandom, all zero but one bit set, or
+ all zero plus a counter that starts at zero.
+
+These constants passed:
+ 14 11 25 16 4 14 24
+ 12 14 25 16 4 14 24
+and these came close:
+ 4 8 15 26 3 22 24
+ 10 8 15 26 3 22 24
+ 11 8 15 26 3 22 24
+-------------------------------------------------------------------------------
+*/
+#define final(a,b,c) \
+{ \
+ c ^= b; c -= rot(b,14); \
+ a ^= c; a -= rot(c,11); \
+ b ^= a; b -= rot(a,25); \
+ c ^= b; c -= rot(b,16); \
+ a ^= c; a -= rot(c,4); \
+ b ^= a; b -= rot(a,14); \
+ c ^= b; c -= rot(b,24); \
+}
+
+/*
+--------------------------------------------------------------------
+ This works on all machines. To be useful, it requires
+ -- that the key be an array of uint32_t's, and
+ -- that the length be the number of uint32_t's in the key
+
+ The function hashword() is identical to hashlittle() on little-endian
+ machines, and identical to hashbig() on big-endian machines,
+ except that the length has to be measured in uint32_ts rather than in
+ bytes. hashlittle() is more complicated than hashword() only because
+ hashlittle() has to dance around fitting the key bytes into registers.
+--------------------------------------------------------------------
+*/
+uint32_t hashword(
+const uint32_t *k, /* the key, an array of uint32_t values */
+size_t length, /* the length of the key, in uint32_ts */
+uint32_t initval) /* the previous hash, or an arbitrary value */
+{
+ uint32_t a,b,c;
+
+ /* Set up the internal state */
+ a = b = c = raninit + (((uint32_t)length)<<2) + initval;
+
+ /*------------------------------------------------- handle most of the key */
+ while (length > 3)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 3;
+ k += 3;
+ }
+
+ /*------------------------------------------- handle the last 3 uint32_t's */
+ switch(length) /* all the case statements fall through */
+ {
+ case 3 : c+=k[2];
+ case 2 : b+=k[1];
+ case 1 : a+=k[0];
+ final(a,b,c);
+ case 0: /* case 0: nothing left to add */
+ break;
+ }
+ /*------------------------------------------------------ report the result */
+ return c;
+}
+
+
+#ifdef SELF_TEST
+
+/*
+--------------------------------------------------------------------
+hashword2() -- same as hashword(), but take two seeds and return two
+32-bit values. pc and pb must both be nonnull, and *pc and *pb must
+both be initialized with seeds. If you pass in (*pb)==0, the output
+(*pc) will be the same as the return value from hashword().
+--------------------------------------------------------------------
+*/
+void hashword2 (
+const uint32_t *k, /* the key, an array of uint32_t values */
+size_t length, /* the length of the key, in uint32_ts */
+uint32_t *pc, /* IN: seed OUT: primary hash value */
+uint32_t *pb) /* IN: more seed OUT: secondary hash value */
+{
+ uint32_t a,b,c;
+
+ /* Set up the internal state */
+ a = b = c = raninit + ((uint32_t)(length<<2)) + *pc;
+ c += *pb;
+
+ /*------------------------------------------------- handle most of the key */
+ while (length > 3)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 3;
+ k += 3;
+ }
+
+ /*------------------------------------------- handle the last 3 uint32_t's */
+ switch(length) /* all the case statements fall through */
+ {
+ case 3 : c+=k[2];
+ case 2 : b+=k[1];
+ case 1 : a+=k[0];
+ final(a,b,c);
+ case 0: /* case 0: nothing left to add */
+ break;
+ }
+ /*------------------------------------------------------ report the result */
+ *pc=c; *pb=b;
+}
+
+#endif /* SELF_TEST */
+
+/*
+-------------------------------------------------------------------------------
+hashlittle() -- hash a variable-length key into a 32-bit value
+ k : the key (the unaligned variable-length array of bytes)
+ length : the length of the key, counting by bytes
+ initval : can be any 4-byte value
+Returns a 32-bit value. Every bit of the key affects every bit of
+the return value. Two keys differing by one or two bits will have
+totally different hash values.
+
+The best hash table sizes are powers of 2. There is no need to do
+mod a prime (mod is sooo slow!). If you need less than 32 bits,
+use a bitmask. For example, if you need only 10 bits, do
+ h = (h & hashmask(10));
+In which case, the hash table should have hashsize(10) elements.
+
+If you are hashing n strings (uint8_t **)k, do it like this:
+ for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h);
+
+By Bob Jenkins, 2006. bob_jenkins@burtleburtle.net. You may use this
+code any way you wish, private, educational, or commercial. It's free.
+
+Use for hash table lookup, or anything where one collision in 2^^32 is
+acceptable. Do NOT use for cryptographic purposes.
+-------------------------------------------------------------------------------
+*/
+
+uint32_t hashlittle( const void *key, size_t length, uint32_t initval)
+{
+ uint32_t a,b,c; /* internal state */
+ union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
+
+ /* Set up the internal state */
+ a = b = c = raninit + ((uint32_t)length) + initval;
+
+ u.ptr = key;
+ if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+#ifdef VALGRIND
+ const uint8_t *k8;
+#endif
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ /*
+ * "k[2]&0xffffff" actually reads beyond the end of the string, but
+ * then masks off the part it's not allowed to read. Because the
+ * string is aligned, the masked-off tail is in the same word as the
+ * rest of the string. Every machine with memory protection I've seen
+ * does it on word boundaries, so is OK with this. But VALGRIND will
+ * still catch it and complain. The masking trick does make the hash
+ * noticably faster for short strings (like English words).
+ */
+#ifndef VALGRIND
+
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
+ case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
+ case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
+ case 6 : b+=k[1]&0xffff; a+=k[0]; break;
+ case 5 : b+=k[1]&0xff; a+=k[0]; break;
+ case 4 : a+=k[0]; break;
+ case 3 : a+=k[0]&0xffffff; break;
+ case 2 : a+=k[0]&0xffff; break;
+ case 1 : a+=k[0]&0xff; break;
+ case 0 : return c; /* zero length strings require no mixing */
+ }
+
+#else /* make valgrind happy */
+
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]; break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
+ case 1 : a+=k8[0]; break;
+ case 0 : return c;
+ }
+
+#endif /* !valgrind */
+
+ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
+ const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
+ const uint8_t *k8;
+
+ /*--------------- all but last block: aligned reads and different mixing */
+ while (length > 12)
+ {
+ a += k[0] + (((uint32_t)k[1])<<16);
+ b += k[2] + (((uint32_t)k[3])<<16);
+ c += k[4] + (((uint32_t)k[5])<<16);
+ mix(a,b,c);
+ length -= 12;
+ k += 6;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[4]+(((uint32_t)k[5])<<16);
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=k[4];
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=k[2];
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=k[0];
+ break;
+ case 1 : a+=k8[0];
+ break;
+ case 0 : return c; /* zero length requires no mixing */
+ }
+
+ } else { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *)key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ a += ((uint32_t)k[1])<<8;
+ a += ((uint32_t)k[2])<<16;
+ a += ((uint32_t)k[3])<<24;
+ b += k[4];
+ b += ((uint32_t)k[5])<<8;
+ b += ((uint32_t)k[6])<<16;
+ b += ((uint32_t)k[7])<<24;
+ c += k[8];
+ c += ((uint32_t)k[9])<<8;
+ c += ((uint32_t)k[10])<<16;
+ c += ((uint32_t)k[11])<<24;
+ mix(a,b,c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c) */
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=((uint32_t)k[11])<<24;
+ case 11: c+=((uint32_t)k[10])<<16;
+ case 10: c+=((uint32_t)k[9])<<8;
+ case 9 : c+=k[8];
+ case 8 : b+=((uint32_t)k[7])<<24;
+ case 7 : b+=((uint32_t)k[6])<<16;
+ case 6 : b+=((uint32_t)k[5])<<8;
+ case 5 : b+=k[4];
+ case 4 : a+=((uint32_t)k[3])<<24;
+ case 3 : a+=((uint32_t)k[2])<<16;
+ case 2 : a+=((uint32_t)k[1])<<8;
+ case 1 : a+=k[0];
+ break;
+ case 0 : return c;
+ }
+ }
+
+ final(a,b,c);
+ return c;
+}
+
+#ifdef SELF_TEST
+
+/*
+ * hashlittle2: return 2 32-bit hash values
+ *
+ * This is identical to hashlittle(), except it returns two 32-bit hash
+ * values instead of just one. This is good enough for hash table
+ * lookup with 2^^64 buckets, or if you want a second hash if you're not
+ * happy with the first, or if you want a probably-unique 64-bit ID for
+ * the key. *pc is better mixed than *pb, so use *pc first. If you want
+ * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)".
+ */
+void hashlittle2(
+ const void *key, /* the key to hash */
+ size_t length, /* length of the key */
+ uint32_t *pc, /* IN: primary initval, OUT: primary hash */
+ uint32_t *pb) /* IN: secondary initval, OUT: secondary hash */
+{
+ uint32_t a,b,c; /* internal state */
+ union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */
+
+ /* Set up the internal state */
+ a = b = c = raninit + ((uint32_t)length) + *pc;
+ c += *pb;
+
+ u.ptr = key;
+ if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) {
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+#ifdef VALGRIND
+ const uint8_t *k8;
+#endif
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ /*
+ * "k[2]&0xffffff" actually reads beyond the end of the string, but
+ * then masks off the part it's not allowed to read. Because the
+ * string is aligned, the masked-off tail is in the same word as the
+ * rest of the string. Every machine with memory protection I've seen
+ * does it on word boundaries, so is OK with this. But VALGRIND will
+ * still catch it and complain. The masking trick does make the hash
+ * noticably faster for short strings (like English words).
+ */
+#ifndef VALGRIND
+
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break;
+ case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break;
+ case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break;
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=k[1]&0xffffff; a+=k[0]; break;
+ case 6 : b+=k[1]&0xffff; a+=k[0]; break;
+ case 5 : b+=k[1]&0xff; a+=k[0]; break;
+ case 4 : a+=k[0]; break;
+ case 3 : a+=k[0]&0xffffff; break;
+ case 2 : a+=k[0]&0xffff; break;
+ case 1 : a+=k[0]&0xff; break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+
+#else /* make valgrind happy */
+
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]; break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */
+ case 1 : a+=k8[0]; break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+
+#endif /* !valgrind */
+
+ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) {
+ const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */
+ const uint8_t *k8;
+
+ /*--------------- all but last block: aligned reads and different mixing */
+ while (length > 12)
+ {
+ a += k[0] + (((uint32_t)k[1])<<16);
+ b += k[2] + (((uint32_t)k[3])<<16);
+ c += k[4] + (((uint32_t)k[5])<<16);
+ mix(a,b,c);
+ length -= 12;
+ k += 6;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ k8 = (const uint8_t *)k;
+ switch(length)
+ {
+ case 12: c+=k[4]+(((uint32_t)k[5])<<16);
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 11: c+=((uint32_t)k8[10])<<16; /* fall through */
+ case 10: c+=k[4];
+ b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 9 : c+=k8[8]; /* fall through */
+ case 8 : b+=k[2]+(((uint32_t)k[3])<<16);
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */
+ case 6 : b+=k[2];
+ a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 5 : b+=k8[4]; /* fall through */
+ case 4 : a+=k[0]+(((uint32_t)k[1])<<16);
+ break;
+ case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */
+ case 2 : a+=k[0];
+ break;
+ case 1 : a+=k8[0];
+ break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+
+ } else { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *)key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ a += ((uint32_t)k[1])<<8;
+ a += ((uint32_t)k[2])<<16;
+ a += ((uint32_t)k[3])<<24;
+ b += k[4];
+ b += ((uint32_t)k[5])<<8;
+ b += ((uint32_t)k[6])<<16;
+ b += ((uint32_t)k[7])<<24;
+ c += k[8];
+ c += ((uint32_t)k[9])<<8;
+ c += ((uint32_t)k[10])<<16;
+ c += ((uint32_t)k[11])<<24;
+ mix(a,b,c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c) */
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=((uint32_t)k[11])<<24;
+ case 11: c+=((uint32_t)k[10])<<16;
+ case 10: c+=((uint32_t)k[9])<<8;
+ case 9 : c+=k[8];
+ case 8 : b+=((uint32_t)k[7])<<24;
+ case 7 : b+=((uint32_t)k[6])<<16;
+ case 6 : b+=((uint32_t)k[5])<<8;
+ case 5 : b+=k[4];
+ case 4 : a+=((uint32_t)k[3])<<24;
+ case 3 : a+=((uint32_t)k[2])<<16;
+ case 2 : a+=((uint32_t)k[1])<<8;
+ case 1 : a+=k[0];
+ break;
+ case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */
+ }
+ }
+
+ final(a,b,c);
+ *pc=c; *pb=b;
+}
+
+#endif /* SELF_TEST */
+
+#if 0 /* currently not used */
+
+/*
+ * hashbig():
+ * This is the same as hashword() on big-endian machines. It is different
+ * from hashlittle() on all machines. hashbig() takes advantage of
+ * big-endian byte ordering.
+ */
+uint32_t hashbig( const void *key, size_t length, uint32_t initval)
+{
+ uint32_t a,b,c;
+ union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */
+
+ /* Set up the internal state */
+ a = b = c = raninit + ((uint32_t)length) + initval;
+
+ u.ptr = key;
+ if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) {
+ const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */
+#ifdef VALGRIND
+ const uint8_t *k8;
+#endif
+
+ /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += k[0];
+ b += k[1];
+ c += k[2];
+ mix(a,b,c);
+ length -= 12;
+ k += 3;
+ }
+
+ /*----------------------------- handle the last (probably partial) block */
+ /*
+ * "k[2]<<8" actually reads beyond the end of the string, but
+ * then shifts out the part it's not allowed to read. Because the
+ * string is aligned, the illegal read is in the same word as the
+ * rest of the string. Every machine with memory protection I've seen
+ * does it on word boundaries, so is OK with this. But VALGRIND will
+ * still catch it and complain. The masking trick does make the hash
+ * noticably faster for short strings (like English words).
+ */
+#ifndef VALGRIND
+
+ switch(length)
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=k[2]&0xffffff00; b+=k[1]; a+=k[0]; break;
+ case 10: c+=k[2]&0xffff0000; b+=k[1]; a+=k[0]; break;
+ case 9 : c+=k[2]&0xff000000; b+=k[1]; a+=k[0]; break;
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=k[1]&0xffffff00; a+=k[0]; break;
+ case 6 : b+=k[1]&0xffff0000; a+=k[0]; break;
+ case 5 : b+=k[1]&0xff000000; a+=k[0]; break;
+ case 4 : a+=k[0]; break;
+ case 3 : a+=k[0]&0xffffff00; break;
+ case 2 : a+=k[0]&0xffff0000; break;
+ case 1 : a+=k[0]&0xff000000; break;
+ case 0 : return c; /* zero length strings require no mixing */
+ }
+
+#else /* make valgrind happy */
+
+ k8 = (const uint8_t *)k;
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=k[2]; b+=k[1]; a+=k[0]; break;
+ case 11: c+=((uint32_t)k8[10])<<8; /* fall through */
+ case 10: c+=((uint32_t)k8[9])<<16; /* fall through */
+ case 9 : c+=((uint32_t)k8[8])<<24; /* fall through */
+ case 8 : b+=k[1]; a+=k[0]; break;
+ case 7 : b+=((uint32_t)k8[6])<<8; /* fall through */
+ case 6 : b+=((uint32_t)k8[5])<<16; /* fall through */
+ case 5 : b+=((uint32_t)k8[4])<<24; /* fall through */
+ case 4 : a+=k[0]; break;
+ case 3 : a+=((uint32_t)k8[2])<<8; /* fall through */
+ case 2 : a+=((uint32_t)k8[1])<<16; /* fall through */
+ case 1 : a+=((uint32_t)k8[0])<<24; break;
+ case 0 : return c;
+ }
+
+#endif /* !VALGRIND */
+
+ } else { /* need to read the key one byte at a time */
+ const uint8_t *k = (const uint8_t *)key;
+
+ /*--------------- all but the last block: affect some 32 bits of (a,b,c) */
+ while (length > 12)
+ {
+ a += ((uint32_t)k[0])<<24;
+ a += ((uint32_t)k[1])<<16;
+ a += ((uint32_t)k[2])<<8;
+ a += ((uint32_t)k[3]);
+ b += ((uint32_t)k[4])<<24;
+ b += ((uint32_t)k[5])<<16;
+ b += ((uint32_t)k[6])<<8;
+ b += ((uint32_t)k[7]);
+ c += ((uint32_t)k[8])<<24;
+ c += ((uint32_t)k[9])<<16;
+ c += ((uint32_t)k[10])<<8;
+ c += ((uint32_t)k[11]);
+ mix(a,b,c);
+ length -= 12;
+ k += 12;
+ }
+
+ /*-------------------------------- last block: affect all 32 bits of (c) */
+ switch(length) /* all the case statements fall through */
+ {
+ case 12: c+=k[11];
+ case 11: c+=((uint32_t)k[10])<<8;
+ case 10: c+=((uint32_t)k[9])<<16;
+ case 9 : c+=((uint32_t)k[8])<<24;
+ case 8 : b+=k[7];
+ case 7 : b+=((uint32_t)k[6])<<8;
+ case 6 : b+=((uint32_t)k[5])<<16;
+ case 5 : b+=((uint32_t)k[4])<<24;
+ case 4 : a+=k[3];
+ case 3 : a+=((uint32_t)k[2])<<8;
+ case 2 : a+=((uint32_t)k[1])<<16;
+ case 1 : a+=((uint32_t)k[0])<<24;
+ break;
+ case 0 : return c;
+ }
+ }
+
+ final(a,b,c);
+ return c;
+}
+
+#endif /* 0 == currently not used */
+
+#ifdef SELF_TEST
+
+/* used for timings */
+void driver1()
+{
+ uint8_t buf[256];
+ uint32_t i;
+ uint32_t h=0;
+ time_t a,z;
+
+ time(&a);
+ for (i=0; i<256; ++i) buf[i] = 'x';
+ for (i=0; i<1; ++i)
+ {
+ h = hashlittle(&buf[0],1,h);
+ }
+ time(&z);
+ if (z-a > 0) printf("time %d %.8x\n", z-a, h);
+}
+
+/* check that every input bit changes every output bit half the time */
+#define HASHSTATE 1
+#define HASHLEN 1
+#define MAXPAIR 60
+#define MAXLEN 70
+void driver2()
+{
+ uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1];
+ uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z;
+ uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE];
+ uint32_t x[HASHSTATE],y[HASHSTATE];
+ uint32_t hlen;
+
+ printf("No more than %d trials should ever be needed \n",MAXPAIR/2);
+ for (hlen=0; hlen < MAXLEN; ++hlen)
+ {
+ z=0;
+ for (i=0; i<hlen; ++i) /*----------------------- for each input byte, */
+ {
+ for (j=0; j<8; ++j) /*------------------------ for each input bit, */
+ {
+ for (m=1; m<8; ++m) /*------------ for serveral possible initvals, */
+ {
+ for (l=0; l<HASHSTATE; ++l)
+ e[l]=f[l]=g[l]=h[l]=x[l]=y[l]=~((uint32_t)0);
+
+ /*---- check that every output bit is affected by that input bit */
+ for (k=0; k<MAXPAIR; k+=2)
+ {
+ uint32_t finished=1;
+ /* keys have one bit different */
+ for (l=0; l<hlen+1; ++l) {a[l] = b[l] = (uint8_t)0;}
+ /* have a and b be two keys differing in only one bit */
+ a[i] ^= (k<<j);
+ a[i] ^= (k>>(8-j));
+ c[0] = hashlittle(a, hlen, m);
+ b[i] ^= ((k+1)<<j);
+ b[i] ^= ((k+1)>>(8-j));
+ d[0] = hashlittle(b, hlen, m);
+ /* check every bit is 1, 0, set, and not set at least once */
+ for (l=0; l<HASHSTATE; ++l)
+ {
+ e[l] &= (c[l]^d[l]);
+ f[l] &= ~(c[l]^d[l]);
+ g[l] &= c[l];
+ h[l] &= ~c[l];
+ x[l] &= d[l];
+ y[l] &= ~d[l];
+ if (e[l]|f[l]|g[l]|h[l]|x[l]|y[l]) finished=0;
+ }
+ if (finished) break;
+ }
+ if (k>z) z=k;
+ if (k==MAXPAIR)
+ {
+ printf("Some bit didn't change: ");
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x ",
+ e[0],f[0],g[0],h[0],x[0],y[0]);
+ printf("i %d j %d m %d len %d\n", i, j, m, hlen);
+ }
+ if (z==MAXPAIR) goto done;
+ }
+ }
+ }
+ done:
+ if (z < MAXPAIR)
+ {
+ printf("Mix success %2d bytes %2d initvals ",i,m);
+ printf("required %d trials\n", z/2);
+ }
+ }
+ printf("\n");
+}
+
+/* Check for reading beyond the end of the buffer and alignment problems */
+void driver3()
+{
+ uint8_t buf[MAXLEN+20], *b;
+ uint32_t len;
+ uint8_t q[] = "This is the time for all good men to come to the aid of their country...";
+ uint32_t h;
+ uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country...";
+ uint32_t i;
+ uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country...";
+ uint32_t j;
+ uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country...";
+ uint32_t ref,x,y;
+ uint8_t *p;
+
+ printf("Endianness. These lines should all be the same (for values filled in):\n");
+ printf("%.8x %.8x %.8x\n",
+ hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13),
+ hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13),
+ hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13));
+ p = q;
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ p = &qq[1];
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ p = &qqq[2];
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ p = &qqqq[3];
+ printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n",
+ hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13),
+ hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13),
+ hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13),
+ hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13),
+ hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13),
+ hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13));
+ printf("\n");
+
+ /* check that hashlittle2 and hashlittle produce the same results */
+ i=47; j=0;
+ hashlittle2(q, sizeof(q), &i, &j);
+ if (hashlittle(q, sizeof(q), 47) != i)
+ printf("hashlittle2 and hashlittle mismatch\n");
+
+ /* check that hashword2 and hashword produce the same results */
+ len = raninit;
+ i=47, j=0;
+ hashword2(&len, 1, &i, &j);
+ if (hashword(&len, 1, 47) != i)
+ printf("hashword2 and hashword mismatch %x %x\n",
+ i, hashword(&len, 1, 47));
+
+ /* check hashlittle doesn't read before or after the ends of the string */
+ for (h=0, b=buf+1; h<8; ++h, ++b)
+ {
+ for (i=0; i<MAXLEN; ++i)
+ {
+ len = i;
+ for (j=0; j<i; ++j) *(b+j)=0;
+
+ /* these should all be equal */
+ ref = hashlittle(b, len, (uint32_t)1);
+ *(b+i)=(uint8_t)~0;
+ *(b-1)=(uint8_t)~0;
+ x = hashlittle(b, len, (uint32_t)1);
+ y = hashlittle(b, len, (uint32_t)1);
+ if ((ref != x) || (ref != y))
+ {
+ printf("alignment error: %.8x %.8x %.8x %d %d\n",ref,x,y,
+ h, i);
+ }
+ }
+ }
+}
+
+/* check for problems with nulls */
+ void driver4()
+{
+ uint8_t buf[1];
+ uint32_t h,i,state[HASHSTATE];
+
+
+ buf[0] = ~0;
+ for (i=0; i<HASHSTATE; ++i) state[i] = 1;
+ printf("These should all be different\n");
+ for (i=0, h=0; i<8; ++i)
+ {
+ h = hashlittle(buf, 0, h);
+ printf("%2ld 0-byte strings, hash is %.8x\n", i, h);
+ }
+}
+
+
+int main()
+{
+ driver1(); /* test that the key is hashed: used for timings */
+ driver2(); /* test that whole key is hashed thoroughly */
+ driver3(); /* test that nothing but the key is hashed */
+ driver4(); /* test hashing multiple buffers (all buffers are null) */
+ return 1;
+}
+
+#endif /* SELF_TEST */
diff --git a/usr.sbin/nsd/lookup3.h b/usr.sbin/nsd/lookup3.h
new file mode 100644
index 00000000000..06211fdde22
--- /dev/null
+++ b/usr.sbin/nsd/lookup3.h
@@ -0,0 +1,71 @@
+/*
+ * util/storage/lookup3.h - header file for hashing functions.
+ *
+ * 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 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 header definitions for the hash functions we use.
+ * The hash functions are public domain (see lookup3.c).
+ */
+
+#ifndef UTIL_STORAGE_LOOKUP3_H
+#define UTIL_STORAGE_LOOKUP3_H
+
+/**
+ * Hash key made of 4byte chunks.
+ * @param k: the key, an array of uint32_t values
+ * @param length: the length of the key, in uint32_ts
+ * @param initval: the previous hash, or an arbitrary value
+ * @return: hash value.
+ */
+uint32_t hashword(const uint32_t *k, size_t length, uint32_t initval);
+
+/**
+ * Hash key data.
+ * @param k: the key, array of uint8_t
+ * @param length: the length of the key, in uint8_ts
+ * @param initval: the previous hash, or an arbitrary value
+ * @return: hash value.
+ */
+uint32_t hashlittle(const void *k, size_t length, uint32_t initval);
+
+/**
+ * Set the randomisation initial value, set this before threads start,
+ * and before hashing stuff (because it changes subsequent results).
+ * @param v: value
+ */
+void hash_set_raninit(uint32_t v);
+
+#endif /* UTIL_STORAGE_LOOKUP3_H */
diff --git a/usr.sbin/nsd/nsd.conf.sample.in b/usr.sbin/nsd/nsd.conf.sample.in
index e7db1bf08b5..cf3e0b0c7bd 100644
--- a/usr.sbin/nsd/nsd.conf.sample.in
+++ b/usr.sbin/nsd/nsd.conf.sample.in
@@ -99,6 +99,20 @@ server:
# Verbosity level.
# verbosity: 0
+ # RRLconfig
+ # Response Rate Limiting, size of the hashtable. Default 1000000.
+ # rrl-size: 1000000
+
+ # Response Rate Limiting, maximum QPS allowed (from one query source).
+ # Default 200. If set to 0, ratelimiting is disabled. Also set
+ # rrl-whitelist-ratelimit to 0 to disable ratelimit processing.
+ # rrl-ratelimit: 200
+
+ # Response Rate Limiting, maximum QPS allowed (from one query source)
+ # for whitelisted types. Default 2000.
+ # rrl-whitelist-ratelimit: 2000
+ # RRLend
+
# key for zone 1
key:
name: mskey
@@ -173,6 +187,21 @@ zone:
# set local interface for sending notifies
outgoing-interface: 10.0.0.15
+ # RRLconfig
+ # Response Rate Limiting, whitelist types
+ # rrl-whitelist: nxdomain
+ # rrl-whitelist: error
+ # rrl-whitelist: referral
+ # rrl-whitelist: any
+ # rrl-whitelist: rrsig
+ # rrl-whitelist: wildcard
+ # rrl-whitelist: nodata
+ # rrl-whitelist: dnskey
+ # rrl-whitelist: positive
+ # rrl-whitelist: all
+ # RRLend
+
+
# keys for zone 2
key:
name: "sec1_key"
diff --git a/usr.sbin/nsd/nsd.h b/usr.sbin/nsd/nsd.h
index aaf034fd2cb..1dce4d95477 100644
--- a/usr.sbin/nsd/nsd.h
+++ b/usr.sbin/nsd/nsd.h
@@ -223,6 +223,7 @@ int server_init(struct nsd *nsd);
int server_prepare(struct nsd *nsd);
void server_main(struct nsd *nsd);
void server_child(struct nsd *nsd);
+void server_shutdown(struct nsd *nsd);
/* extra domain numbers for temporary domains */
#define EXTRA_DOMAIN_NUMBERS 1024
diff --git a/usr.sbin/nsd/nsec3.h b/usr.sbin/nsd/nsec3.h
index 36e9fbc53a8..d55b4825394 100644
--- a/usr.sbin/nsd/nsec3.h
+++ b/usr.sbin/nsd/nsec3.h
@@ -9,7 +9,7 @@
#ifndef NSEC3_H
#define NSEC3_H
-#include <config.h>
+#include "config.h"
#ifdef NSEC3
struct domain;
diff --git a/usr.sbin/nsd/options.c b/usr.sbin/nsd/options.c
index 60dbef010d7..721c763383e 100644
--- a/usr.sbin/nsd/options.c
+++ b/usr.sbin/nsd/options.c
@@ -6,13 +6,14 @@
* See LICENSE for the license.
*
*/
-#include <config.h>
+#include "config.h"
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include "options.h"
#include "query.h"
#include "tsig.h"
+#include "rrl.h"
#include "configyyrename.h"
nsd_options_t* nsd_options = 0;
@@ -63,6 +64,11 @@ nsd_options_t* nsd_options_create(region_type* region)
opt->difffile = DIFFFILE;
opt->xfrdfile = XFRDFILE;
opt->xfrd_reload_timeout = 10;
+#ifdef RATELIMIT
+ opt->rrl_size = RRL_BUCKETS;
+ opt->rrl_ratelimit = RRL_LIMIT/2;
+ opt->rrl_whitelist_ratelimit = RRL_WLIST_LIMIT/2;
+#endif
nsd_options = opt;
return opt;
}
@@ -231,6 +237,9 @@ zone_options_t* zone_options_create(region_type* region)
zone->provide_xfr = 0;
zone->outgoing_interface = 0;
zone->allow_axfr_fallback = 1;
+#ifdef RATELIMIT
+ zone->rrl_whitelist = 0;
+#endif
return zone;
}
diff --git a/usr.sbin/nsd/options.h b/usr.sbin/nsd/options.h
index 6da56fe9e4f..5845b6eaa9f 100644
--- a/usr.sbin/nsd/options.h
+++ b/usr.sbin/nsd/options.h
@@ -64,6 +64,15 @@ struct nsd_options {
const char* nsid;
int xfrd_reload_timeout;
+#ifdef RATELIMIT
+ /** number of buckets in rrl hashtable */
+ size_t rrl_size;
+ /** max qps for queries, 0 is nolimit */
+ size_t rrl_ratelimit;
+ /** max qps for whitelisted queries, 0 is nolimit */
+ size_t rrl_whitelist_ratelimit;
+#endif
+
region_type* region;
};
@@ -87,6 +96,9 @@ struct zone_options {
acl_options_t* notify;
acl_options_t* provide_xfr;
acl_options_t* outgoing_interface;
+#ifdef RATELIMIT
+ uint16_t rrl_whitelist; /* bitmap with rrl types */
+#endif
uint8_t allow_axfr_fallback;
uint8_t notify_retry;
};
diff --git a/usr.sbin/nsd/packet.c b/usr.sbin/nsd/packet.c
index e08544cbf4c..a4ab76e9511 100644
--- a/usr.sbin/nsd/packet.c
+++ b/usr.sbin/nsd/packet.c
@@ -7,7 +7,7 @@
*
*/
-#include <config.h>
+#include "config.h"
#include <string.h>
diff --git a/usr.sbin/nsd/query.h b/usr.sbin/nsd/query.h
index ff2eb0a6840..24fafd447ca 100644
--- a/usr.sbin/nsd/query.h
+++ b/usr.sbin/nsd/query.h
@@ -119,6 +119,11 @@ struct query {
domain_type *axfr_current_domain;
rrset_type *axfr_current_rrset;
uint16_t axfr_current_rr;
+
+#ifdef RATELIMIT
+ /* if we encountered a wildcard, its domain */
+ domain_type *wildcard_domain;
+#endif
};
diff --git a/usr.sbin/nsd/rrl.c b/usr.sbin/nsd/rrl.c
new file mode 100644
index 00000000000..01da9d75ff1
--- /dev/null
+++ b/usr.sbin/nsd/rrl.c
@@ -0,0 +1,463 @@
+
+/* rrl.c - Response Rate Limiting for NSD.
+ * By W.C.A. Wijngaards
+ * Copyright 2012, NLnet Labs.
+ * BSD, see LICENSE.
+ */
+#include "config.h"
+#include <errno.h>
+#include <ctype.h>
+#include "rrl.h"
+#include "util.h"
+#include "lookup3.h"
+#include "options.h"
+
+#ifdef RATELIMIT
+
+#ifdef HAVE_MMAP
+#include <sys/mman.h>
+#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS)
+#define MAP_ANONYMOUS MAP_ANON
+#endif
+#endif /* HAVE_MMAP */
+
+
+/**
+ * The rate limiting data structure bucket, this represents one rate of
+ * packets from a single source.
+ * Smoothed average rates.
+ */
+struct rrl_bucket {
+ /* the source netmask */
+ uint64_t source;
+ /* rate, in queries per second, which due to rate=r(t)+r(t-1)/2 is
+ * equal to double the queries per second */
+ uint32_t rate;
+ /* counter for queries arrived in this second */
+ uint32_t counter;
+ /* timestamp, which time is the time of the counter, the rate is from
+ * one timestep before that. */
+ int32_t stamp;
+ /* flags for the source mask and type */
+ uint16_t flags;
+};
+
+/* the (global) array of RRL buckets */
+static struct rrl_bucket* rrl_array = NULL;
+static size_t rrl_array_size = RRL_BUCKETS;
+static uint32_t rrl_ratelimit = RRL_LIMIT; /* 2x qps */
+static uint32_t rrl_whitelist_ratelimit = RRL_WLIST_LIMIT; /* 2x qps */
+
+/* the array of mmaps for the children (saved between reloads) */
+static void** rrl_maps = NULL;
+static size_t rrl_maps_num = 0;
+
+/* from NSD4 for RRL logs */
+static char* wiredname2str(const uint8_t* dname)
+{
+ static char buf[MAXDOMAINLEN*5+3];
+ char* p = buf;
+ uint8_t lablen;
+ if(*dname == 0) {
+ strlcpy(buf, ".", sizeof(buf));
+ return buf;
+ }
+ lablen = *dname++;
+ while(lablen) {
+ while(lablen--) {
+ uint8_t ch = *dname++;
+ if (isalnum(ch) || ch == '-' || ch == '_') {
+ *p++ = ch;
+ } else if (ch == '.' || ch == '\\') {
+ *p++ = '\\';
+ *p++ = ch;
+ } else {
+ snprintf(p, 5, "\\%03u", (unsigned int)ch);
+ p += 4;
+ }
+ }
+ lablen = *dname++;
+ *p++ = '.';
+ }
+ *p++ = 0;
+ return buf;
+}
+
+void rrl_mmap_init(int numch, size_t numbuck, size_t lm, size_t wlm)
+{
+#ifdef HAVE_MMAP
+ size_t i;
+#endif
+ if(numbuck != 0)
+ rrl_array_size = numbuck;
+ rrl_ratelimit = lm*2;
+ rrl_whitelist_ratelimit = wlm*2;
+#ifdef HAVE_MMAP
+ /* allocate the ratelimit hashtable in a memory map so it is
+ * preserved across reforks (every child its own table) */
+ rrl_maps_num = (size_t)numch;
+ rrl_maps = (void**)xalloc(sizeof(void*)*rrl_maps_num);
+ for(i=0; i<rrl_maps_num; i++) {
+ rrl_maps[i] = mmap(NULL,
+ sizeof(struct rrl_bucket)*rrl_array_size,
+ PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
+ if(rrl_maps[i] == MAP_FAILED) {
+ log_msg(LOG_ERR, "rrl: mmap failed: %s",
+ strerror(errno));
+ exit(1);
+ }
+ memset(rrl_maps[i], 0,
+ sizeof(struct rrl_bucket)*rrl_array_size);
+ }
+#else
+ (void)numch;
+ rrl_maps_num = 0;
+ rrl_maps = NULL;
+#endif
+}
+
+void rrl_set_limit(size_t lm, size_t wlm)
+{
+ rrl_ratelimit = lm*2;
+ rrl_whitelist_ratelimit = wlm*2;
+}
+
+void rrl_init(size_t ch)
+{
+ if(!rrl_maps || ch >= rrl_maps_num)
+ rrl_array = xalloc_zero(sizeof(struct rrl_bucket)*rrl_array_size);
+#ifdef HAVE_MMAP
+ else rrl_array = (struct rrl_bucket*)rrl_maps[ch];
+#endif
+}
+
+/** return the source netblock of the query, this is the genuine source
+ * for genuine queries and the target for reflected packets */
+static uint64_t rrl_get_source(query_type* query, uint16_t* c2)
+{
+ /* we take a /24 for IPv4 and /64 for IPv6 */
+ /* note there is an IPv6 subnet, that maps
+ * to the same buckets as IPv4 space, but there is a flag in c2
+ * that makes the hash different */
+#ifdef INET6
+ if( ((struct sockaddr_in*)&query->addr)->sin_family == AF_INET) {
+ *c2 = 0;
+ return ((struct sockaddr_in*)&query->addr)->
+ sin_addr.s_addr & htonl(0xffffff00);
+ } else {
+ uint64_t s;
+ *c2 = rrl_ip6;
+ memmove(&s, &((struct sockaddr_in6*)&query->addr)->sin6_addr,
+ sizeof(s));
+ return s;
+ }
+#else
+ *c2 = 0;
+ return query->addr.sin_addr.s_addr & htonl(0xffffff00);
+#endif
+}
+
+/** debug source to string */
+static const char* rrlsource2str(uint64_t s, uint16_t c2)
+{
+ static char buf[64];
+ struct in_addr a4;
+#ifdef INET6
+ if(c2) {
+ /* IPv6 */
+ struct in6_addr a6;
+ memset(&a6, 0, sizeof(a6));
+ memmove(&a6, &s, sizeof(s));
+ if(!inet_ntop(AF_INET6, &a6, buf, sizeof(buf)))
+ strlcpy(buf, "[ip6 ntop failed]", sizeof(buf));
+ else strlcat(buf, "/64", sizeof(buf));
+ return buf;
+ }
+#endif
+ /* ipv4 */
+ a4.s_addr = (uint32_t)s;
+ if(!inet_ntop(AF_INET, &a4, buf, sizeof(buf)))
+ strlcpy(buf, "[ip4 ntop failed]", sizeof(buf));
+ else strlcat(buf, "/24", sizeof(buf));
+ return buf;
+}
+
+enum rrl_type rrlstr2type(const char* s)
+{
+ if(strcmp(s, "nxdomain")==0) return rrl_type_nxdomain;
+ else if(strcmp(s, "error")==0) return rrl_type_error;
+ else if(strcmp(s, "referral")==0) return rrl_type_referral;
+ else if(strcmp(s, "any")==0) return rrl_type_any;
+ else if(strcmp(s, "wildcard")==0) return rrl_type_wildcard;
+ else if(strcmp(s, "nodata")==0) return rrl_type_nodata;
+ else if(strcmp(s, "dnskey")==0) return rrl_type_dnskey;
+ else if(strcmp(s, "positive")==0) return rrl_type_positive;
+ else if(strcmp(s, "rrsig")==0) return rrl_type_rrsig;
+ else if(strcmp(s, "all")==0) return rrl_type_all;
+ return 0; /* unknown */
+}
+
+const char* rrltype2str(enum rrl_type c)
+{
+ switch(c & 0x0fff) {
+ case rrl_type_nxdomain: return "nxdomain";
+ case rrl_type_error: return "error";
+ case rrl_type_referral: return "referral";
+ case rrl_type_any: return "any";
+ case rrl_type_wildcard: return "wildcard";
+ case rrl_type_nodata: return "nodata";
+ case rrl_type_dnskey: return "dnskey";
+ case rrl_type_positive: return "positive";
+ case rrl_type_rrsig: return "rrsig";
+ case rrl_type_all: return "all";
+ }
+ return "unknown";
+}
+
+/** classify the query in a number of different types, each has separate
+ * ratelimiting, so that positive queries are not impeded by others */
+static uint16_t rrl_classify(query_type* query, const uint8_t** d,
+ size_t* d_len)
+{
+ if(RCODE(query->packet) == RCODE_NXDOMAIN) {
+ if(query->zone && query->zone->apex) {
+ *d = dname_name(domain_dname(query->zone->apex));
+ *d_len = domain_dname(query->zone->apex)->name_size;
+ }
+ return rrl_type_nxdomain;
+ }
+ if(RCODE(query->packet) != RCODE_OK) {
+ if(query->zone && query->zone->apex) {
+ *d = dname_name(domain_dname(query->zone->apex));
+ *d_len = domain_dname(query->zone->apex)->name_size;
+ }
+ return rrl_type_error;
+ }
+ if(query->delegation_domain) {
+ *d = dname_name(domain_dname(query->delegation_domain));
+ *d_len = domain_dname(query->delegation_domain)->name_size;
+ return rrl_type_referral;
+ }
+ if(query->qtype == TYPE_ANY) {
+ if(query->qname) {
+ *d = dname_name(query->qname);
+ *d_len = query->qname->name_size;
+ }
+ return rrl_type_any;
+ }
+ if(query->qtype == TYPE_RRSIG) {
+ if(query->qname) {
+ *d = dname_name(query->qname);
+ *d_len = query->qname->name_size;
+ }
+ return rrl_type_rrsig;
+ }
+ if(query->wildcard_domain) {
+ *d = dname_name(domain_dname(query->wildcard_domain));
+ *d_len = domain_dname(query->wildcard_domain)->name_size;
+ return rrl_type_wildcard;
+ }
+ if(ANCOUNT(query->packet) == 0) {
+ if(query->zone && query->zone->apex) {
+ *d = dname_name(domain_dname(query->zone->apex));
+ *d_len = domain_dname(query->zone->apex)->name_size;
+ }
+ return rrl_type_nodata;
+ }
+ if(query->qtype == TYPE_DNSKEY) {
+ if(query->qname) {
+ *d = dname_name(query->qname);
+ *d_len = query->qname->name_size;
+ }
+ return rrl_type_dnskey;
+ }
+ /* positive */
+ if(query->qname) {
+ *d = dname_name(query->qname);
+ *d_len = query->qname->name_size;
+ }
+ return rrl_type_positive;
+}
+
+/** Examine the query and return hash and source of netblock. */
+static void examine_query(query_type* query, uint32_t* hash, uint64_t* source,
+ uint16_t* flags, uint32_t* lm)
+{
+ /* compile a binary string representing the query */
+ uint16_t c, c2;
+ /* size with 16 bytes to spare */
+ uint8_t buf[MAXDOMAINLEN + sizeof(*source) + sizeof(c) + 16];
+ const uint8_t* dname = NULL; size_t dname_len;
+ uint32_t r = 0x267fcd16;
+
+ *source = rrl_get_source(query, &c2);
+ c = rrl_classify(query, &dname, &dname_len);
+ if(query->zone && query->zone->opts &&
+ (query->zone->opts->rrl_whitelist & c))
+ *lm = rrl_whitelist_ratelimit;
+ if(*lm == 0) return;
+ c |= c2;
+ *flags = c;
+ memmove(buf, source, sizeof(*source));
+ memmove(buf+sizeof(*source), &c, sizeof(c));
+
+ DEBUG(DEBUG_QUERY, 1, (LOG_INFO, "rrl_examine type %s name %s", rrltype2str(c), dname?wiredname2str(dname):"NULL"));
+
+ /* and hash it */
+ if(dname && dname_len <= MAXDOMAINLEN) {
+ memmove(buf+sizeof(*source)+sizeof(c), dname, dname_len);
+ *hash = hashlittle(buf, sizeof(*source)+sizeof(c)+dname_len, r);
+ } else
+ *hash = hashlittle(buf, sizeof(*source)+sizeof(c), r);
+}
+
+/* age the bucket because elapsed time steps have gone by */
+static void rrl_attenuate_bucket(struct rrl_bucket* b, int32_t elapsed)
+{
+ if(elapsed > 16) {
+ b->rate = 0;
+ } else {
+ /* divide rate /2 for every elapsed time step, because
+ * the counters in the inbetween steps were 0 */
+ /* r(t) = 0 + 0/2 + 0/4 + .. + oldrate/2^dt */
+ b->rate >>= elapsed;
+ /* we know that elapsed >= 2 */
+ b->rate += (b->counter>>(elapsed-1));
+ }
+}
+
+/** log a message about ratelimits */
+static void
+rrl_msg(query_type* query, const char* str)
+{
+ uint16_t c, c2, wl = 0;
+ const uint8_t* d = NULL;
+ size_t d_len;
+ uint64_t s;
+ if(verbosity < 2) return;
+ s = rrl_get_source(query, &c2);
+ c = rrl_classify(query, &d, &d_len) | c2;
+ if(query->zone && query->zone->opts &&
+ (query->zone->opts->rrl_whitelist & c))
+ wl = 1;
+ log_msg(LOG_INFO, "ratelimit %s %s type %s%s target %s",
+ str, d?wiredname2str(d):"", rrltype2str(c),
+ wl?"(whitelisted)":"", rrlsource2str(s, c2));
+}
+
+/** true if the query used to be blocked by the ratelimit */
+static int
+used_to_block(uint32_t rate, uint32_t counter, uint32_t lm)
+{
+ return rate >= lm || counter+rate/2 >= lm;
+}
+
+/** update the rate in a ratelimit bucket, return actual rate */
+uint32_t rrl_update(query_type* query, uint32_t hash, uint64_t source,
+ uint16_t flags, int32_t now, uint32_t lm)
+{
+ struct rrl_bucket* b = &rrl_array[hash % rrl_array_size];
+
+ DEBUG(DEBUG_QUERY, 1, (LOG_INFO, "source %llx hash %x oldrate %d oldcount %d stamp %d",
+ (long long unsigned)source, hash, b->rate, b->counter, b->stamp));
+
+ /* check if different source */
+ if(b->source != source || b->flags != flags) {
+ /* initialise */
+ /* potentially the wrong limit here, used lower nonwhitelim */
+ if(verbosity >=2 &&
+ used_to_block(b->rate, b->counter, rrl_ratelimit))
+ log_msg(LOG_INFO, "ratelimit unblock ~ type %s target %s",
+ rrltype2str(b->flags),
+ rrlsource2str(b->source, b->flags));
+ b->source = source;
+ b->flags = flags;
+ b->counter = 1;
+ b->rate = 0;
+ b->stamp = now;
+ return 1;
+ }
+ /* this is the same source */
+
+ /* check if old, zero or smooth it */
+ /* circular arith for time */
+ if(now - b->stamp == 1) {
+ /* very busy bucket and time just stepped one step */
+ int oldblock = used_to_block(b->rate, b->counter, lm);
+ b->rate = b->rate/2 + b->counter;
+ if(oldblock && b->rate < lm)
+ rrl_msg(query, "unblock");
+ b->counter = 1;
+ b->stamp = now;
+ } else if(now - b->stamp > 0) {
+ /* older bucket */
+ int olderblock = used_to_block(b->rate, b->counter, lm);
+ rrl_attenuate_bucket(b, now - b->stamp);
+ if(olderblock && b->rate < lm)
+ rrl_msg(query, "unblock");
+ b->counter = 1;
+ b->stamp = now;
+ } else if(now != b->stamp) {
+ /* robust, timestamp from the future */
+ if(used_to_block(b->rate, b->counter, lm))
+ rrl_msg(query, "unblock");
+ b->rate = 0;
+ b->counter = 1;
+ b->stamp = now;
+ } else {
+ /* bucket is from the current timestep, update counter */
+ b->counter ++;
+
+ /* log what is blocked for operational debugging */
+ if(b->counter + b->rate/2 == lm && b->rate < lm)
+ rrl_msg(query, "block");
+ }
+
+ /* return max from current rate and projected next-value for rate */
+ /* so that if the rate increases suddenly very high, it is
+ * stopped halfway into the time step */
+ if(b->counter > b->rate/2)
+ return b->counter + b->rate/2;
+ return b->rate;
+}
+
+int rrl_process_query(query_type* query)
+{
+ uint64_t source;
+ uint32_t hash;
+ int32_t now = (int32_t)time(NULL);
+ uint32_t lm = rrl_ratelimit;
+ uint16_t flags;
+ if(rrl_ratelimit == 0 && rrl_whitelist_ratelimit == 0)
+ return 0;
+
+ /* examine query */
+ examine_query(query, &hash, &source, &flags, &lm);
+
+ if(lm == 0)
+ return 0; /* no limit for this */
+
+ /* update rate */
+ return (rrl_update(query, hash, source, flags, now, lm) >= lm);
+}
+
+query_state_type rrl_slip(query_type* query)
+{
+ /* discard half the packets, randomly */
+ if((random() & 0x1)) {
+ /* set TC on the rest */
+ TC_SET(query->packet);
+ ANCOUNT_SET(query->packet, 0);
+ NSCOUNT_SET(query->packet, 0);
+ ARCOUNT_SET(query->packet, 0);
+ if(query->qname)
+ /* header, type, class, qname */
+ buffer_set_position(query->packet,
+ QHEADERSZ+4+query->qname->name_size);
+ else buffer_set_position(query->packet, QHEADERSZ);
+ return QUERY_PROCESSED;
+ }
+ return QUERY_DISCARDED;
+}
+
+#endif /* RATELIMIT */
diff --git a/usr.sbin/nsd/rrl.h b/usr.sbin/nsd/rrl.h
new file mode 100644
index 00000000000..fae8fbf2343
--- /dev/null
+++ b/usr.sbin/nsd/rrl.h
@@ -0,0 +1,71 @@
+/* rrl.h - Response Rate Limiting for NSD.
+ * By W.C.A. Wijngaards
+ * Copyright 2012, NLnet Labs.
+ * BSD, see LICENSE.
+ */
+#ifndef RRL_H
+#define RRL_H
+#include "query.h"
+
+/** the classification types for the rrl */
+enum rrl_type {
+ /* classification types */
+ rrl_type_nxdomain = 0x01,
+ rrl_type_error = 0x02,
+ rrl_type_referral = 0x04,
+ rrl_type_any = 0x08,
+ rrl_type_wildcard = 0x10,
+ rrl_type_nodata = 0x20,
+ rrl_type_dnskey = 0x40,
+ rrl_type_positive = 0x80,
+ rrl_type_rrsig = 0x100,
+
+ /* all classification types */
+ rrl_type_all = 0x1ff,
+ /* to distinguish between ip4 and ip6 netblocks, used in code */
+ rrl_ip6 = 0x8000
+};
+
+/** Number of buckets */
+#define RRL_BUCKETS 1000000
+/** default rrl limit, in 2x qps , the default is 200 qps */
+#define RRL_LIMIT 400
+/** default whitelist rrl limit, in 2x qps, default is thus 2000 qps */
+#define RRL_WLIST_LIMIT 4000
+
+/**
+ * Initialize for n children (optional, otherwise no mmaps used)
+ * ratelimits lm and wlm are in qps (this routines x2s them for internal use).
+ */
+void rrl_mmap_init(int numch, size_t numbuck, size_t lm, size_t wlm);
+
+/**
+ * Initialize rate limiting (for this child server process)
+ */
+void rrl_init(size_t ch);
+
+/**
+ * Process query that happens, the query structure contains the
+ * information about the query and the answer.
+ * returns true if the query is ratelimited.
+ */
+int rrl_process_query(query_type* query);
+
+/**
+ * Deny the query, with slip.
+ * Returns DISCARD or PROCESSED(with TC flag).
+ */
+query_state_type rrl_slip(query_type* query);
+
+/** convert classification type to string */
+const char* rrltype2str(enum rrl_type c);
+/** convert string to classification type */
+enum rrl_type rrlstr2type(const char* s);
+
+/** for unit test, update rrl bucket; return rate */
+uint32_t rrl_update(query_type* query, uint32_t hash, uint64_t source,
+ uint16_t flags, int32_t now, uint32_t lm);
+/** set the rate limit counters, pass variables in qps */
+void rrl_set_limit(size_t lm, size_t wlm);
+
+#endif /* RRL_H */
diff --git a/usr.sbin/nsd/tsig-openssl.c b/usr.sbin/nsd/tsig-openssl.c
index 7e6004b86b9..797f7fbf2ab 100644
--- a/usr.sbin/nsd/tsig-openssl.c
+++ b/usr.sbin/nsd/tsig-openssl.c
@@ -31,7 +31,7 @@ tsig_openssl_init_algorithm(region_type* region,
hmac_algorithm = EVP_get_digestbyname(digest);
if (!hmac_algorithm) {
- log_msg(LOG_ERR, "%s digest not available", digest);
+ /* skip but don't error */
return 0;
}
@@ -58,21 +58,18 @@ tsig_openssl_init_algorithm(region_type* region,
int
tsig_openssl_init(region_type *region)
{
+ int count = 0;
OpenSSL_add_all_digests();
- /* TODO: walk lookup supported algorithms table */
- if (!tsig_openssl_init_algorithm(region, "md5", "hmac-md5","hmac-md5.sig-alg.reg.int."))
- return 0;
+ count += tsig_openssl_init_algorithm(region, "md5", "hmac-md5","hmac-md5.sig-alg.reg.int.");
#ifdef HAVE_EVP_SHA1
- if (!tsig_openssl_init_algorithm(region, "sha1", "hmac-sha1", "hmac-sha1."))
- return 0;
+ count += tsig_openssl_init_algorithm(region, "sha1", "hmac-sha1", "hmac-sha1.");
#endif /* HAVE_EVP_SHA1 */
#ifdef HAVE_EVP_SHA256
- if (!tsig_openssl_init_algorithm(region, "sha256", "hmac-sha256", "hmac-sha256."))
- return 0;
+ count += tsig_openssl_init_algorithm(region, "sha256", "hmac-sha256", "hmac-sha256.");
#endif /* HAVE_EVP_SHA256 */
- return 1;
+ return count;
}
static void
diff --git a/usr.sbin/nsd/tsig.c b/usr.sbin/nsd/tsig.c
index be1ca85ce44..cf2872b563e 100644
--- a/usr.sbin/nsd/tsig.c
+++ b/usr.sbin/nsd/tsig.c
@@ -36,18 +36,6 @@ typedef struct tsig_algorithm_table tsig_algorithm_table_type;
static tsig_algorithm_table_type *tsig_algorithm_table;
static size_t max_algo_digest_size = 0;
-tsig_lookup_algorithm_table tsig_supported_algorithms[] = {
- { TSIG_HMAC_MD5, "hmac-md5" },
-#ifdef HAVE_EVP_SHA1
- { TSIG_HMAC_SHA1, "hmac-sha1" },
-#endif /* HAVE_EVP_SHA1 */
-
-#ifdef HAVE_EVP_SHA256
- { TSIG_HMAC_SHA256, "hmac-sha256" },
-#endif /* HAVE_EVP_SHA256 */
- { 0, NULL }
-};
-
static void
tsig_digest_variables(tsig_record_type *tsig, int tsig_timers_only)
{
@@ -181,19 +169,6 @@ tsig_get_algorithm_by_name(const char *name)
return NULL;
}
-/*
- * Find an HMAC algorithm based on its id.
- */
-tsig_algorithm_type *
-tsig_get_algorithm_by_id(uint8_t alg)
-{
- int i=0;
- for (/*empty*/; tsig_supported_algorithms[i].id > 0; i++) {
- if (tsig_supported_algorithms[i].id == alg)
- return tsig_get_algorithm_by_name(tsig_supported_algorithms[i].short_name);
- }
- return NULL;
-}
const char *
tsig_error(int error_code)
@@ -593,8 +568,6 @@ tsig_parse_rr(tsig_record_type *tsig, buffer_type *packet)
tsig->rr_region, buffer_current(packet), tsig->other_size);
buffer_skip(packet, tsig->other_size);
tsig->status = TSIG_OK;
- tsig->error_code = TSIG_ERROR_NOERROR;
-
return 1;
}
diff --git a/usr.sbin/nsd/tsig.h b/usr.sbin/nsd/tsig.h
index a142d65d936..f09a07e5aba 100644
--- a/usr.sbin/nsd/tsig.h
+++ b/usr.sbin/nsd/tsig.h
@@ -156,11 +156,6 @@ void tsig_add_algorithm(tsig_algorithm_type *algorithm);
tsig_algorithm_type *tsig_get_algorithm_by_name(const char *name);
/*
- * Find an HMAC algorithm based on its identifier.
- */
-tsig_algorithm_type *tsig_get_algorithm_by_id(uint8_t alg);
-
-/*
* Return a descriptive error message based on the TSIG error code.
*/
const char *tsig_error(int error_code);
diff --git a/usr.sbin/nsd/xfrd.c b/usr.sbin/nsd/xfrd.c
index 7cb0ebbdcc0..ea24abad853 100644
--- a/usr.sbin/nsd/xfrd.c
+++ b/usr.sbin/nsd/xfrd.c
@@ -1129,6 +1129,12 @@ xfrd_xfr_process_tsig(xfrd_zone_t* zone, buffer_type* packet)
}
if(zone->tsig.status == TSIG_OK) {
have_tsig = 1;
+ if (zone->tsig.error_code != TSIG_ERROR_NOERROR) {
+ log_msg(LOG_ERR, "xfrd: zone %s, from %s: tsig error "
+ "(%s)", zone->apex_str,
+ zone->master->ip_address_spec,
+ tsig_error(zone->tsig.error_code));
+ }
}
if(have_tsig) {
/* strip the TSIG resource record off... */
@@ -1203,7 +1209,10 @@ xfrd_parse_received_xfr_packet(xfrd_zone_t* zone, buffer_type* packet,
RCODE(packet) == RCODE_FORMAT) {
return xfrd_packet_notimpl;
}
- return xfrd_packet_bad;
+ if (RCODE(packet) != RCODE_NOTAUTH) {
+ /* RFC 2845: If NOTAUTH, client should do TSIG checking */
+ return xfrd_packet_bad;
+ }
}
/* check TSIG */
if(zone->master->key_options) {
@@ -1213,6 +1222,10 @@ xfrd_parse_received_xfr_packet(xfrd_zone_t* zone, buffer_type* packet,
return xfrd_packet_bad;
}
}
+ if (RCODE(packet) == RCODE_NOTAUTH) {
+ return xfrd_packet_bad;
+ }
+
buffer_skip(packet, QHEADERSZ);
/* skip question section */