[packages/libspf2] Rel 4. Fix silent truncation of SPF records past 64 ip4 mechanisms, unbounded DNS lookups through ne

arekm arekm at pld-linux.org
Tue Nov 3 11:46:24 CET 2026


commit be76952d3f72cf6dc88f63b5ac59334c418f7aaf
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date:   Tue Nov 3 09:10:14 2026 +0100

    Rel 4. Fix silent truncation of SPF records past 64 ip4 mechanisms,
    unbounded DNS lookups through nested includes (DoS), RFC 7208
    conformance and upstream PR fixes; add regression tests

 dns-cache-precedence.patch |  23 ++
 dns-mech-limit.patch       |  56 +++++
 dns-resolv-num-rr.patch    |  41 ++++
 domain-truncate.patch      |  85 +++++++
 duplicate-exp.patch        |  29 +++
 empty-domain-spec.patch    |  84 +++++++
 fix-include.patch          |  17 ++
 libspf2-tests.c            | 594 +++++++++++++++++++++++++++++++++++++++++++++
 libspf2.spec               |  57 ++++-
 long-values.patch          | 428 ++++++++++++++++++++++++++++++++
 macro-truncate.patch       |  31 +++
 malformed-domain.patch     |  50 ++++
 query-record-uaf.patch     |  23 ++
 record-mech-len.patch      |  97 ++++++++
 redirect-last.patch        |  91 +++++++
 rfc-error-results.patch    |  71 ++++++
 16 files changed, 1774 insertions(+), 3 deletions(-)
---
diff --git a/libspf2.spec b/libspf2.spec
index 82a7091..72b6157 100644
--- a/libspf2.spec
+++ b/libspf2.spec
@@ -1,26 +1,54 @@
 # TODO
 # ./configure[3000]: AX_WITH_PERL: not found - needed after regeneration
+#
+# Conditional build:
+%bcond_without	tests	# PLD regression and upstream parser tests
 
 Summary:	Implementation of the SPF specification
 Summary(pl.UTF-8):	Implementacja specyfikacji SPF
 Name:		libspf2
 Version:	1.2.11
-Release:	3
+Release:	4
 License:	LGPL
 Group:		Libraries
 # Source0:	http://www.libspf2.org/spf/%{name}-%{version}.tar.gz
 Source0:	https://github.com/shevek/libspf2/tarball/4915c30#/%{name}.tar.gz
 # Source0-md5:	ad5f1b48e4f2b5561df99ca7cbf30e92
+Source1:	%{name}-tests.c
 Patch0:		%{name}-link.patch
 Patch1:		0001-remove-libreplace-unneeded-on-Linux.patch
-# https://github.com/shevek/libspf2/pull/44
+# CVE-2023-42118; https://github.com/shevek/libspf2/pull/44
 Patch2:         integer-underflow.patch
 Patch3:         spf_dns-include-std-headers.patch
 Patch4:         abolish-spf-rrtype.patch
-URL:		http://www.libspf2.org/
+Patch5:		record-mech-len.patch
+# https://bugs.debian.org/1065792
+Patch6:		fix-include.patch
+# https://github.com/shevek/libspf2/pull/10
+Patch7:		redirect-last.patch
+Patch8:		macro-truncate.patch
+# https://github.com/shevek/libspf2/pull/25
+Patch9:		dns-resolv-num-rr.patch
+# https://github.com/shevek/libspf2/pull/15
+Patch10:	query-record-uaf.patch
+# https://github.com/shevek/libspf2/pull/37
+Patch11:	dns-cache-precedence.patch
+Patch12:	rfc-error-results.patch
+Patch13:	duplicate-exp.patch
+Patch14:	long-values.patch
+Patch15:	domain-truncate.patch
+Patch16:	empty-domain-spec.patch
+Patch17:	dns-mech-limit.patch
+Patch18:	malformed-domain.patch
+URL:		https://github.com/shevek/libspf2
 BuildRequires:	autoconf >= 2.59
 BuildRequires:	automake
 BuildRequires:	libtool
+%if %{with tests}
+BuildRequires:	perl(Test::More)
+BuildRequires:	perl(Text::ParseWords)
+BuildRequires:	perl-base
+%endif
 Obsoletes:	libspf_alt
 BuildRoot:	%{tmpdir}/%{name}-%{version}-root-%(id -u -n)
 
@@ -81,6 +109,20 @@ Statyczna biblioteka libspf2.
 %patch -P2 -p1
 %patch -P3 -p1
 %patch -P4 -p1
+%patch -P5 -p1
+%patch -P6 -p1
+%patch -P7 -p1
+%patch -P8 -p1
+%patch -P9 -p1
+%patch -P10 -p1
+%patch -P11 -p1
+%patch -P12 -p1
+%patch -P13 -p1
+%patch -P14 -p1
+%patch -P15 -p1
+%patch -P16 -p1
+%patch -P17 -p1
+%patch -P18 -p1
 
 %build
 %{__libtoolize}
@@ -91,6 +133,15 @@ Statyczna biblioteka libspf2.
 %configure
 %{__make}
 
+%if %{with tests}
+%{__cc} %{rpmcflags} %{rpmcppflags} %{rpmldflags} -Isrc/include -I. \
+	-o libspf2-tests %{SOURCE1} src/libspf2/.libs/libspf2.a -lresolv -lpthread
+./libspf2-tests
+# other upstream suites fail without PLD patches too; test_live needs network
+cd tests
+./run_single_parser
+%endif
+
 %install
 rm -rf $RPM_BUILD_ROOT
 %{__make} install \
diff --git a/dns-cache-precedence.patch b/dns-cache-precedence.patch
new file mode 100644
index 0000000..518aba0
--- /dev/null
+++ b/dns-cache-precedence.patch
@@ -0,0 +1,23 @@
+From dc0fcf8e53cf3b45eef70d56fed2a3200da7c672 Mon Sep 17 00:00:00 2001
+From: Simon Arlott <sa.me.uk>
+Date: Fri, 13 Aug 2021 23:07:41 +0100
+Subject: [PATCH] spf_dns_cache.c: Fix expression precedence
+
+Fixes #31.
+---
+ src/libspf2/spf_dns_cache.c | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/src/libspf2/spf_dns_cache.c b/src/libspf2/spf_dns_cache.c
+index 16c9819..0011e14 100644
+--- a/src/libspf2/spf_dns_cache.c
++++ b/src/libspf2/spf_dns_cache.c
+@@ -342,7 +342,7 @@ SPF_dns_cache_rr_fixup(SPF_dns_cache_config_t *spfhook,
+ 		cached_rr->ttl = spfhook->min_ttl;
+ 
+     if ( cached_rr->ttl < spfhook->txt_ttl
+-			&& cached_rr->rr_type == ns_t_txt || cached_rr->rr_type == ns_t_spf )
++			&& (cached_rr->rr_type == ns_t_txt || cached_rr->rr_type == ns_t_spf) )
+ 		cached_rr->ttl = spfhook->txt_ttl;
+ 
+     if ( cached_rr->ttl < spfhook->err_ttl
diff --git a/dns-mech-limit.patch b/dns-mech-limit.patch
new file mode 100644
index 0000000..5ec292f
--- /dev/null
+++ b/dns-mech-limit.patch
@@ -0,0 +1,56 @@
+RFC 7208 4.6.4: at most 10 mechanisms and modifiers that do DNS lookups
+per SPF check. Each include started its own count from zero, so a record
+with 10 includes of a record with 10 includes, nested up to the depth
+limit of 20, made 10^20 lookups; one sender could stall the receiving
+MTA. The count now goes through includes, and the term over the limit
+is a permerror before its lookup rather than after it.
+
+--- a/src/libspf2/spf_interpret.c
++++ b/src/libspf2/spf_interpret.c
+@@ -718,7 +718,14 @@
+ 	 * evaluate the mechanisms
+ 	 */
+ 
+-#define SPF_ADD_DNS_MECH() do { spf_response->num_dns_mech++; } while(0)
++/* RFC 7208 4.6.4: at most max_dns_mech DNS terms per check, includes
++ * counted in; one more is a permerror before its lookup. */
++#define SPF_ADD_DNS_MECH() do { \
++		if (++spf_response->num_dns_mech > spf_server->max_dns_mech) { \
++			SPF_FREE_LOOKUP_DATA(); \
++			return DONE(SPF_RESULT_PERMERROR, SPF_REASON_NONE, SPF_E_BIG_DNS); \
++		} \
++	} while(0)
+ 
+ #define SPF_MAYBE_SKIP_CIDR() \
+ 	do { \
+@@ -755,13 +762,6 @@
+ 	mech = spf_record->mech_first;
+ 	for (m = 0; m < spf_record->num_mech; m++) {
+ 
+-		/* This is as good a place as any. */
+-		/* XXX Rip this out and put it into a macro which can go into inner loops. */
+-		if (spf_response->num_dns_mech > spf_server->max_dns_mech) {
+-			SPF_FREE_LOOKUP_DATA();
+-			return DONE(SPF_RESULT_PERMERROR, SPF_REASON_NONE, SPF_E_BIG_DNS);
+-		}
+-
+ 		data = SPF_mech_data(mech);
+ 		data_end = SPF_mech_end_data(mech);
+ 
+@@ -1120,6 +1120,8 @@
+ 				}
+ 				spf_response->spf_record_exp = spf_record;
+ 				SPF_ASSERT_NOTNULL(spf_response->spf_record_exp);
++				/* the limit is per check, not per included record */
++				spf_response->num_dns_mech = save_spf_response->num_dns_mech;
+ 			}
+ 			/*
+ 			 * find out whether this configuration passes
+@@ -1150,6 +1152,7 @@
+ 				spf_response_subr = spf_response;
+ 				spf_response = save_spf_response;
+ 				save_spf_response = NULL;
++				spf_response->num_dns_mech = spf_response_subr->num_dns_mech;
+ 
+ 				/* Rewrite according to prefix of include */
+ 				switch (SPF_response_result(spf_response_subr)) {
diff --git a/dns-resolv-num-rr.patch b/dns-resolv-num-rr.patch
new file mode 100644
index 0000000..6265b5c
--- /dev/null
+++ b/dns-resolv-num-rr.patch
@@ -0,0 +1,41 @@
+From b2719864620ecfb4477326a74edbbb643356f2ed Mon Sep 17 00:00:00 2001
+From: Telford Tendys <ttndy at cpan.org>
+Date: Sun, 1 Apr 2018 03:20:15 +0000
+Subject: [PATCH] Not properly counting number of results.
+
+Symptom is that AUTHORITY section will cause earlier sections to be
+thrown away when debug is enabled. Potentially could lose DNS results in
+other situations as well.
+---
+ src/libspf2/spf_dns_resolv.c | 4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/src/libspf2/spf_dns_resolv.c b/src/libspf2/spf_dns_resolv.c
+index 9dacafe..f98c5a3 100644
+--- a/src/libspf2/spf_dns_resolv.c
++++ b/src/libspf2/spf_dns_resolv.c
+@@ -383,6 +383,7 @@ SPF_dns_resolv_lookup(SPF_dns_server_t *spf_dns_server,
+ 
+ 
+ 	/* FIXME  the error handling from here on is suspect at best */
++	spfrr->num_rr = 0;
+ 	for (ns_sect = 0; ns_sect < num_ns_sect; ns_sect++) {
+ 		/* We pass this point if:
+ 		 * - We are the 'answer' section.
+@@ -397,7 +398,6 @@ SPF_dns_resolv_lookup(SPF_dns_server_t *spf_dns_server,
+ 		if (spf_dns_server->debug > 1)
+ 			SPF_debugf("%s:  %d", ns_sects[ns_sect].name, nrec);
+ 
+-		spfrr->num_rr = 0;
+ 		cnt = 0;
+ 		for (i = 0; i < nrec; i++) {
+ 			err = ns_parserr(&ns_handle, ns_sects[ns_sect].number, i, &rr);
+@@ -592,7 +592,7 @@ SPF_dns_resolv_lookup(SPF_dns_server_t *spf_dns_server,
+ 			}
+ 		}
+ 
+-		spfrr->num_rr = cnt;
++		spfrr->num_rr += cnt;
+ 	}
+ 
+ 	if (spfrr->num_rr == 0)
diff --git a/domain-truncate.patch b/domain-truncate.patch
new file mode 100644
index 0000000..142ecba
--- /dev/null
+++ b/domain-truncate.patch
@@ -0,0 +1,85 @@
+RFC 7208 7.3: an expanded domain name over 253 chars is truncated on
+the left, label by label, until it fits; libspf2 queried the whole name
+(a, mx, ptr, include, redirect, exists and the exp= target). A trailing
+root dot does not count towards the 253.
+
+--- a/src/include/spf_internal.h
++++ b/src/include/spf_internal.h
+@@ -19,6 +19,8 @@
+ #ifndef INC_SPF_INTERNAL
+ #define INC_SPF_INTERNAL
+ 
++#include <string.h>
++
+ #ifndef TRUE
+ #define TRUE 1
+ #define FALSE 0
+@@ -137,6 +139,23 @@
+ 
+ char *SPF_sanitize( SPF_server_t *spf_server, char *str );
+ 
++/* RFC 7208 7.3: an expanded domain name over 253 chars loses labels on
++ * the left until it fits; a trailing dot (the root) does not count. */
++static inline const char *SPF_domain_truncate( const char *domain )
++{
++	size_t			 len = strlen(domain);
++	const char		*dot;
++
++	if (len > 0 && domain[len - 1] == '.')
++		len--;
++
++	while (len > 253 && (dot = strchr(domain, '.')) != NULL) {
++		len -= dot + 1 - domain;
++		domain = dot + 1;
++	}
++	return domain;
++}
++
+ void SPF_print_sizeof(void);
+ 
+ /**
+--- a/src/libspf2/spf_get_exp.c
++++ b/src/libspf2/spf_get_exp.c
+@@ -153,9 +153,11 @@
+ 	resolver = spf_server->resolver;
+ 
+ 	if (resolver->get_exp)
+-		return resolver->get_exp(spf_server, *bufp, bufp, buflenp);
++		return resolver->get_exp(spf_server, SPF_domain_truncate(*bufp),
++						bufp, buflenp);
+ 
+-	rr_txt = SPF_dns_lookup(resolver, *bufp, ns_t_txt, TRUE);
++	rr_txt = SPF_dns_lookup(resolver, SPF_domain_truncate(*bufp),
++					ns_t_txt, TRUE);
+ 	if (rr_txt == NULL) {
+ 		SPF_dns_rr_free(rr_txt);
+ 		RETURN_DEFAULT_EXP();
+--- a/src/libspf2/spf_interpret.c
++++ b/src/libspf2/spf_interpret.c
+@@ -743,7 +743,7 @@
+ 				SPF_FREE_LOOKUP_DATA();					\
+ 				return DONE_PERMERR(err);				\
+ 			}											\
+-			lookup = buf;								\
++			lookup = SPF_domain_truncate(buf);			\
+ 		}												\
+ 	} while(0)
+ #define SPF_FREE_LOOKUP_DATA() \
+@@ -1063,7 +1063,7 @@
+ 				SPF_FREE_LOOKUP_DATA();
+ 				return DONE_PERMERR( err );
+ 			}
+-			lookup = buf;
++			lookup = SPF_domain_truncate(buf);
+ 
+ 			/* XXX Maintain a stack depth here. Limit at 10. */
+ 			if (strcmp(lookup, spf_request->cur_dom) == 0) {
+@@ -1222,7 +1222,7 @@
+ 				SPF_FREE_LOOKUP_DATA();
+ 				return DONE_TEMPERR( err );
+ 			}
+-			lookup = buf;
++			lookup = SPF_domain_truncate(buf);
+ 
+ 			rr_a = SPF_dns_lookup(resolver, lookup, ns_t_a, FALSE );
+ 
diff --git a/duplicate-exp.patch b/duplicate-exp.patch
new file mode 100644
index 0000000..d24b946
--- /dev/null
+++ b/duplicate-exp.patch
@@ -0,0 +1,29 @@
+RFC 7208 6: exp= may appear at most once, otherwise the result is
+permerror; libspf2 compiled every exp= without complaint.
+
+--- a/src/libspf2/spf_compile.c
++++ b/src/libspf2/spf_compile.c
+@@ -1234,6 +1234,7 @@
+ 	const SPF_mechtype_t*redirect_mechtype = NULL;
+ 	int					 redirect_prefix = PREFIX_UNKNOWN;
+ 	const char			*redirect_val_start;
++	int					 num_exp = 0;
+ 
+ 
+ 	/*
+@@ -1496,6 +1497,15 @@
+ 			if ( STREQ_SIZEOF(name_start, "redirect=") )
+ 				goto compile_mech;
+ 
++			/* RFC 7208 6: at most once, else permerror */
++			if ( STREQ_SIZEOF_N(name_start, "exp", name_len) && num_exp++ > 0 ) {
++				SPF_response_add_error_ptr(spf_response, SPF_E_SYNTAX,
++								NULL, name_start,
++								"Multiple exp= modifiers");
++				p = val_end;
++				break;
++			}
++
+ 			p++;
+ 			val_start = p;
+ 			err = SPF_c_mod_add(spf_server,
diff --git a/empty-domain-spec.patch b/empty-domain-spec.patch
new file mode 100644
index 0000000..b83d7d7
--- /dev/null
+++ b/empty-domain-spec.patch
@@ -0,0 +1,84 @@
+RFC 7208 5, 6.2: a ':' or '=' is followed by a domain-spec, which is
+never empty, but "a:", "a:/24", "include:", "exists:", "redirect=",
+"exp=" and the like compiled, printed back as records that no longer
+compile, and an empty value made SPF_c_parse_cidr() step before the
+start of its input. The RFC 7208 test suite expects permerror
+(*-empty-domain); test_parser.txt expected "a:/32//12" to compile.
+
+--- a/src/libspf2/spf_compile.c
++++ b/src/libspf2/spf_compile.c
+@@ -228,10 +228,11 @@
+ 	memset(data, 0, sizeof(SPF_data_cidr_t));
+ 	data->parm_type = PARM_CIDR;
+ 
+-	/* Find the beginning of the CIDR length notation.
+-	 * XXX This assumes that there is a non-digit in the string.
+-	 * This is always true for SPF records with domainspecs, since
+-	 * there has to be an = or a : before it. */
++	/* src starts after the ':' or at the '/', so it may be empty. */
++	if (*src_len == 0)
++		return SPF_E_SUCCESS;
++
++	/* Find the beginning of the CIDR length notation. */
+ 	idx = *src_len - 1;
+ 	while (idx > 0 && isdigit( (unsigned char)(src[idx]) ))
+ 		idx--;
+@@ -249,6 +250,8 @@
+ 				return err;
+ 			/* now back up and see if there is a ipv4 cidr length */
+ 			*src_len = idx - 1;	/* The index of the first '/' */
++			if (*src_len == 0)
++				return SPF_E_SUCCESS;
+ 			idx = *src_len - 1;	/* Last character of what is before. */
+ 			while (idx > 0 && isdigit( (unsigned char)(src[idx]) ))
+ 				idx--;
+@@ -730,6 +733,14 @@
+ 		}
+ 	}
+ 
++	/* RFC 7208 5, 6.1: a ':' or '=' is followed by a domain-spec, which
++	 * is never empty; only the '/' form passes CIDR_ONLY. */
++	if (cidr_ok != CIDR_ONLY && src_len == 0)
++		return SPF_response_add_error_ptr(spf_response,
++						SPF_E_MISSING_OPT,
++						NULL, src,
++						"Empty domain-spec after mechanism");
++
+ 	return SPF_c_parse_macro(spf_server, spf_response,
+ 			data, data_used, data_avail,
+ 			src, src_len, big_err, is_mod);
+@@ -1518,6 +1529,14 @@
+ 				p = val_end;
+ 				break;
+ 			}
++			/* RFC 7208 6.2: exp= takes a domain-spec, never empty */
++			if ( STREQ_SIZEOF_N(name_start, "exp", name_len) && p + 1 == val_end ) {
++				SPF_response_add_error_ptr(spf_response, SPF_E_MISSING_OPT,
++								NULL, name_start,
++								"Empty domain-spec after exp=");
++				p = val_end;
++				break;
++			}
+ 
+ 			p++;
+ 			val_start = p;
+--- a/tests/test_parser.txt
++++ b/tests/test_parser.txt
+@@ -162,13 +162,13 @@
+ 
+ spftest spf "v=spf1 a:/32//12"
+ rec-in          /.*/ SPF record in:  v=spf1 a:/32//12
+-err-msg         /.*/ no errors
+-rec-out         /.*/ SPF record:  v=spf1 a//12
++err-msg         /.*/ /Empty domain-spec/
++rec-out         /.*/ Unknown
+ 
+ spftest spf "v=spf1 a:/32//128"
+ rec-in          /.*/ SPF record in:  v=spf1 a:/32//128
+-err-msg         /.*/ no errors
+-rec-out         /.*/ SPF record:  v=spf1 a
++err-msg         /.*/ /Empty domain-spec/
++rec-out         /.*/ Unknown
+ 
+ spftest spf "v=spf1 a:/x32//12"
+ rec-in          /.*/ SPF record in:  v=spf1 a:/x32//12
diff --git a/fix-include.patch b/fix-include.patch
new file mode 100644
index 0000000..19aefdc
--- /dev/null
+++ b/fix-include.patch
@@ -0,0 +1,17 @@
+Description: Fix FTBFS with -Werror=implicit-function-declaration
+  Include string.h in spf_utils.c to get a declaration for memset().
+Author: Michael Hudson-Doyle <michael.hudson at ubuntu.com>
+Origin: vendor
+Bug-Debian: https://bugs.debian.org/1065792
+Reviewed-By: Andreas Metzler <ametzler at debian.org>
+
+--- a/src/libspf2/spf_utils.c
++++ b/src/libspf2/spf_utils.c
+@@ -19,6 +19,7 @@
+ #ifdef STDC_HEADERS
+ # include <stdlib.h>	   /* malloc / free */
+ # include <ctype.h>		/* isupper / tolower */
++# include <string.h>       /* memset */
+ #endif
+ 
+ #ifdef HAVE_MEMORY_H
diff --git a/libspf2-tests.c b/libspf2-tests.c
new file mode 100644
index 0000000..f988e04
--- /dev/null
+++ b/libspf2-tests.c
@@ -0,0 +1,594 @@
+/*
+ * Regression tests for the PLD patches to libspf2, run against the built
+ * library with offline DNS (zone resolver plus a layer returning chosen
+ * h_errno values).
+ *
+ * What holds:
+ *  - a record keeps every mechanism up to 255 of them and 16384 compiled
+ *    bytes; past that it is a permerror with SPF_E_BIG_MECH, through DNS,
+ *    fallback and include;
+ *  - modifiers past those limits are ignored, never an error (RFC 7208 6);
+ *    RFC 7208 sets no limit on a single literal, modifier or explanation;
+ *  - the checked domain's own record gives RFC 7208 results: permerror for
+ *    one that does not compile, temperror for DNS errors other than
+ *    NXDOMAIN, none for an answer without TXT records or for a malformed
+ *    domain (RFC 7208 4.3), permerror when that domain is an include target;
+ *  - at most 10 DNS terms per check, include targets counted in, so nested
+ *    includes cannot multiply the lookups (RFC 7208 4.6.4);
+ *  - redirect= applies only when no mechanism matched; redirect= and exp=
+ *    appear at most once;
+ *  - a ':' or '=' with an empty domain-spec is a permerror (RFC 7208 5);
+ *  - %{xN} keeps the rightmost N parts (RFC 7208 7.3);
+ *  - a domain name over 253 chars loses labels on the left (RFC 7208 7.3);
+ *  - a record prints back as written;
+ *  - the response does not keep a pointer to the freed record;
+ *  - the DNS cache keeps a long TTL of SPF-type records.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <netinet/in.h>
+#include <arpa/nameser.h>
+#include <netdb.h>
+
+#include "spf.h"
+#include "spf_dns.h"
+#include "spf_dns_rr.h"
+#include "spf_dns_zone.h"
+#include "spf_dns_cache.h"
+#include "spf_record.h"
+#include "spf_internal.h"
+
+#define LIMIT	16384
+
+static SPF_server_t		*srv;
+static SPF_dns_server_t	*zone;
+static int				 failures;
+
+static void check(int ok, const char *what, const char *detail)
+{
+	printf("%s %s%s%s\n", ok ? "ok    " : "FAILED", what,
+			detail ? " | " : "", detail ? detail : "");
+	failures += !ok;
+}
+
+static void txt(const char *domain, const char *record)
+{
+	SPF_dns_zone_add_str(zone, domain, ns_t_txt, NETDB_SUCCESS, record);
+}
+
+/* ---- queries ---- */
+
+static void query(const char *what, const char *from, const char *ip,
+		const char *fallback, SPF_result_t want, SPF_errcode_t want_err)
+{
+	SPF_request_t	*req = SPF_request_new(srv);
+	SPF_response_t	*resp = NULL;
+	SPF_errcode_t	 ret;
+	const char		*h;
+	char			 hdr[64], detail[256];
+	int				 ok;
+
+	SPF_request_set_ipv4_str(req, ip);
+	SPF_request_set_env_from(req, from);
+	ret = fallback ? SPF_request_query_fallback(req, &resp, fallback)
+			: SPF_request_query_mailfrom(req, &resp);
+	h = SPF_response_get_received_spf(resp);
+	snprintf(hdr, sizeof(hdr), "Received-SPF: %s ", SPF_strresult(want));
+	ok = SPF_response_result(resp) == want
+			&& SPF_response_errcode(resp) == want_err && ret == want_err
+			&& h != NULL && strncmp(h, hdr, strlen(hdr)) == 0
+			&& resp->spf_record_exp == NULL;
+	snprintf(detail, sizeof(detail), "result=%s errcode=%d ret=%d header=%.40s",
+			SPF_strresult(SPF_response_result(resp)),
+			SPF_response_errcode(resp), ret, h ? h : "(null)");
+	check(ok, what, ok ? NULL : detail);
+	SPF_response_free(resp);
+	SPF_request_free(req);
+}
+
+/* ---- record builders ---- */
+
+static char *rec_new(const char *start)
+{
+	char *b = malloc(1 << 17);
+	sprintf(b, "v=spf1%s", start);
+	return b;
+}
+
+static void add_ip4(char *b, int n)
+{
+	for (int i = 0; i < n; i++)
+		sprintf(b + strlen(b), " ip4:10.%d.%d.1", i / 250, i % 250);
+}
+
+static void add_long(char *b, const char *prefix, int n, int len)
+{
+	for (int i = 0; i < n; i++) {
+		char *p = b + strlen(b);
+		p += sprintf(p, prefix, i);
+		memset(p, 'a', len);
+		p[len] = '\0';
+	}
+}
+
+static size_t compiled_len(const char *rec, int *ok)
+{
+	SPF_response_t	*resp = SPF_response_new(NULL);
+	SPF_record_t	*r = NULL;
+	size_t			 len = 0;
+
+	*ok = SPF_record_compile(srv, resp, &r, rec) == SPF_E_SUCCESS;
+	if (r) {
+		len = r->mech_len;
+		SPF_record_free(r);
+	}
+	SPF_response_free(resp);
+	return len;
+}
+
+/*
+ * "at": the largest record whose mechanism section is exactly LIMIT bytes;
+ * "over": the first one past it. String literals are at most 255 chars,
+ * so the section is filled with long exists: values.
+ */
+static void boundary(char **at, char **over)
+{
+	char *prev = NULL;
+
+	for (int last = 1; last < 256; last++) {
+		char	*b = rec_new(" ip4:192.0.2.1");
+		int		 ok;
+		size_t	 len;
+
+		add_long(b, " exists:%d", 62, 249);
+		add_long(b, " exists:%d", 1, last);
+		strcat(b, " -all");
+		len = compiled_len(b, &ok);
+		if (!ok) {
+			*at = prev;
+			*over = b;
+			return;
+		}
+		free(prev);
+		prev = len == LIMIT ? b : NULL;
+		if (!prev)
+			free(b);
+	}
+	free(prev);
+	*at = *over = NULL;
+}
+
+static void test_limits(void)
+{
+	char *e2o = rec_new(""), *r255 = rec_new(""), *r256 = rec_new("");
+	char *m256 = rec_new(" ip4:192.0.2.1 -all"), *modover = rec_new(" ip4:192.0.2.1 -all");
+	char *modname = rec_new(" ip4:192.0.2.1 -all"), *modexp = rec_new(" ip4:192.0.2.1 -all");
+	char *modlit = rec_new(" ip4:192.0.2.1 -all"), *modmac = rec_new(" ip4:192.0.2.1 -all");
+	char *modbad = rec_new(" ip4:192.0.2.1 -all");
+	char *mech_at = NULL, *mech_over = NULL;
+
+	/* 83 ip4 + 8 ip6 + -all behind include:, as 28bgbqr47._spf._d.mim.ec */
+	add_ip4(e2o, 83);
+	for (int i = 1; i <= 8; i++)
+		sprintf(e2o + strlen(e2o), " ip6:2001:db8:%x::/48", i);
+	strcat(e2o, " -all");
+	txt("e2o-child.test", e2o);
+	txt("e2o.test", "v=spf1 include:e2o-child.test -all");
+	query("mechanism 66 of 92 behind include: matches", "u at e2o.test", "10.0.65.1", NULL,
+			SPF_RESULT_PASS, SPF_E_SUCCESS);
+	query("trailing -all of a 92-mechanism record applies", "u at e2o-child.test", "192.0.2.9",
+			NULL, SPF_RESULT_FAIL, SPF_E_SUCCESS);
+
+	add_ip4(r255, 254); strcat(r255, " ip4:192.0.2.1");
+	add_ip4(r256, 255); strcat(r256, " ip4:192.0.2.1");
+	add_long(m256, " x%d=", 256, 1);
+	add_long(modover, " x%d=", 70, 250);
+	add_long(modname, " x%d", 1, 600);
+	strcat(modname, "=a");
+	add_long(modexp, " x%d=", 255, 1);
+	strcat(modexp, " exp=e.target.test");
+	add_long(modlit, " x%d=", 1, 300);
+	strcat(modmac, " x=");
+	for (int i = 0; i < 150; i++)
+		strcat(modmac, "%{d}");
+	add_long(modbad, " x%d=", 1, 300);
+	strcat(modbad, "%{z}");
+	boundary(&mech_at, &mech_over);
+	check(mech_at != NULL, "record of exactly 16384 compiled bytes built", NULL);
+	if (!mech_at)
+		goto out;
+
+	struct { const char *what, *dom, *rec; SPF_result_t want; SPF_errcode_t err; } c[] = {
+		{ "255 mechanisms",            "mech255.test",  r255,      SPF_RESULT_PASS,      SPF_E_SUCCESS },
+		{ "256 mechanisms",            "mech256.test",  r256,      SPF_RESULT_PERMERROR, SPF_E_BIG_MECH },
+		{ "16384 bytes of mechanisms", "mechat.test",   mech_at,   SPF_RESULT_PASS,      SPF_E_SUCCESS },
+		{ "past 16384 bytes of mechanisms", "mechover.test", mech_over, SPF_RESULT_PERMERROR, SPF_E_BIG_MECH },
+		{ "256 unknown modifiers",     "mod256.test",   m256,      SPF_RESULT_PASS,      SPF_E_SUCCESS },
+		{ "unknown modifiers past 16384 bytes", "modover.test", modover, SPF_RESULT_PASS, SPF_E_SUCCESS },
+		{ "unknown modifier with a 600-char name", "modname.test", modname, SPF_RESULT_PASS, SPF_E_SUCCESS },
+		{ "exp= after 255 unknown modifiers", "modexp.test", modexp, SPF_RESULT_PASS, SPF_E_SUCCESS },
+		{ "unknown modifier with a 300-char literal", "modlit.test", modlit, SPF_RESULT_PASS, SPF_E_SUCCESS },
+		{ "unknown modifier compiled past 511 bytes", "modmac.test", modmac, SPF_RESULT_PASS, SPF_E_SUCCESS },
+		{ "syntax error after a 300-char literal", "modbad.test", modbad, SPF_RESULT_PERMERROR, SPF_E_INVALID_VAR },
+	};
+	char what[128], from[64];
+
+	for (size_t i = 0; i < sizeof(c) / sizeof(*c); i++) {
+		txt(c[i].dom, c[i].rec);
+		snprintf(from, sizeof(from), "u@%s", c[i].dom);
+		snprintf(what, sizeof(what), "%s, own record", c[i].what);
+		query(what, from, "192.0.2.1", NULL, c[i].want, c[i].err);
+		snprintf(what, sizeof(what), "%s, fallback", c[i].what);
+		query(what, "u at nospf.test", "192.0.2.1", c[i].rec, c[i].want, c[i].err);
+	}
+	query("-all behind 256 unknown modifiers", "u at mod256.test", "192.0.2.9", NULL,
+			SPF_RESULT_FAIL, SPF_E_SUCCESS);
+	txt("inclbig.test", "v=spf1 include:mech256.test -all");
+	query("256 mechanisms behind include:", "u at inclbig.test", "192.0.2.1", NULL,
+			SPF_RESULT_PERMERROR, SPF_E_BIG_MECH);
+out:
+	free(e2o); free(r255); free(r256);
+	free(m256); free(modover); free(modname); free(modexp);
+	free(modlit); free(modmac); free(modbad);
+	free(mech_at); free(mech_over);
+}
+
+/* ---- results for the domain's own record ---- */
+
+static SPF_dns_rr_t *fake_lookup(SPF_dns_server_t *s, const char *domain,
+		ns_type rr_type, int should_cache)
+{
+	if (rr_type == ns_t_txt && strcmp(domain, "norecovery.test") == 0)
+		return SPF_dns_rr_new_init(s, domain, rr_type, 0, NO_RECOVERY);
+	if (rr_type == ns_t_txt && strcmp(domain, "unknownerr.test") == 0)
+		return SPF_dns_rr_new_init(s, domain, rr_type, 0, 77);
+	if (rr_type == ns_t_txt && strcmp(domain, "notxt.test") == 0)
+		return SPF_dns_rr_new_init(s, domain, rr_type, 0, NETDB_SUCCESS);
+	/* glibc fails names it cannot encode with NO_RECOVERY */
+	if (domain[0] == '.' || strstr(domain, "..") || strcspn(domain, ".") > 63)
+		return SPF_dns_rr_new_init(s, domain, rr_type, 0, NO_RECOVERY);
+	return SPF_dns_lookup(s->layer_below, domain, rr_type, should_cache);
+}
+
+static void test_results(void)
+{
+	txt("syntax.test", "v=spf1 ip4:300.1.1.1 -all");
+	query("syntax error, own record", "u at syntax.test", "192.0.2.1", NULL,
+			SPF_RESULT_PERMERROR, SPF_E_INVALID_IP4);
+	query("syntax error, fallback", "u at nospf.test", "192.0.2.1",
+			"v=spf1 ip4:300.1.1.1 -all", SPF_RESULT_PERMERROR, SPF_E_INVALID_IP4);
+	query("DNS NO_RECOVERY", "u at norecovery.test", "192.0.2.1", NULL,
+			SPF_RESULT_TEMPERROR, SPF_E_DNS_ERROR);
+	query("DNS unknown h_errno", "u at unknownerr.test", "192.0.2.1", NULL,
+			SPF_RESULT_TEMPERROR, SPF_E_DNS_ERROR);
+	query("DNS success without TXT records", "u at notxt.test", "192.0.2.1", NULL,
+			SPF_RESULT_NONE, SPF_E_NOT_SPF);
+
+	char from[128], rec[128], label[65];
+	memset(label, 'a', 64);
+	label[64] = '\0';
+	snprintf(from, sizeof(from), "u@%s.test", label);
+	query("label of 64 chars", from, "192.0.2.1", NULL,
+			SPF_RESULT_NONE, SPF_E_NOT_SPF);
+	query("empty label", "u at a..test", "192.0.2.1", NULL,
+			SPF_RESULT_NONE, SPF_E_NOT_SPF);
+	query("empty first label", "u at .test", "192.0.2.1", NULL,
+			SPF_RESULT_NONE, SPF_E_NOT_SPF);
+	snprintf(rec, sizeof(rec), "v=spf1 include:%s.test -all", label);
+	txt("badinclude.test", rec);
+	query("include of a malformed domain", "u at badinclude.test", "192.0.2.1",
+			NULL, SPF_RESULT_PERMERROR, SPF_E_NOT_SPF);
+	label[63] = '\0';
+	snprintf(from, sizeof(from), "u@%s.test", label);
+	txt(from + 2, "v=spf1 -all");
+	query("label of 63 chars", from, "192.0.2.1", NULL,
+			SPF_RESULT_FAIL, SPF_E_SUCCESS);
+}
+
+/* ---- DNS lookup limit ---- */
+
+static void test_dns_limit(void)
+{
+	/* include:t counts as one, the target's a terms as the rest */
+	txt("dns10.test", "v=spf1 include:nine.test -all");
+	txt("nine.test", "v=spf1 a a a a a a a a a -all");
+	txt("dns11.test", "v=spf1 include:ten.test -all");
+	txt("ten.test", "v=spf1 a a a a a a a a a a -all");
+	query("10 DNS terms through include", "u at dns10.test", "192.0.2.1", NULL,
+			SPF_RESULT_FAIL, SPF_E_SUCCESS);
+	query("11 DNS terms through include", "u at dns11.test", "192.0.2.1", NULL,
+			SPF_RESULT_PERMERROR, SPF_E_BIG_DNS);
+}
+
+/* ---- redirect= and exp= ---- */
+
+static void explanation(const char *what, const char *from, size_t want_len)
+{
+	SPF_request_t	*req = SPF_request_new(srv);
+	SPF_response_t	*resp = NULL;
+	const char		*e;
+	char			 detail[64];
+
+	SPF_request_set_ipv4_str(req, "192.0.2.1");
+	SPF_request_set_env_from(req, from);
+	SPF_request_query_mailfrom(req, &resp);
+	e = SPF_response_get_explanation(resp);
+	snprintf(detail, sizeof(detail), "length %zu", e ? strlen(e) : 0);
+	check(e && strlen(e) == want_len, what, detail);
+	SPF_response_free(resp);
+	SPF_request_free(req);
+}
+
+static void test_modifiers(void)
+{
+	txt("target.test", "v=spf1 -all");
+	txt("open.test", "v=spf1 +all");
+	txt("redirfirst.test", "v=spf1 redirect=target.test ip4:192.0.2.1");
+	txt("redirtwice.test", "v=spf1 redirect=target.test redirect=open.test");
+	txt("redirbad.test", "v=spf1 redirect=open.test redirect=%{z}");
+	txt("exponce.test", "v=spf1 -all exp=e.target.test");
+	txt("exptwice.test", "v=spf1 -all exp=e.target.test exp=f.target.test");
+
+	query("redirect= before a matching mechanism", "u at redirfirst.test", "192.0.2.1",
+			NULL, SPF_RESULT_PASS, SPF_E_SUCCESS);
+	query("redirect= when nothing matched", "u at redirfirst.test", "192.0.2.9",
+			NULL, SPF_RESULT_FAIL, SPF_E_SUCCESS);
+	query("two redirect=", "u at redirtwice.test", "192.0.2.1", NULL,
+			SPF_RESULT_PERMERROR, SPF_E_SYNTAX);
+	query("valid redirect= then invalid redirect=", "u at redirbad.test", "192.0.2.1",
+			NULL, SPF_RESULT_PERMERROR, SPF_E_SYNTAX);
+	query("one exp=", "u at exponce.test", "192.0.2.1", NULL,
+			SPF_RESULT_FAIL, SPF_E_SUCCESS);
+	query("two exp=", "u at exptwice.test", "192.0.2.1", NULL,
+			SPF_RESULT_PERMERROR, SPF_E_SYNTAX);
+
+	char text[601];
+	memset(text, 'a', 600);
+	text[600] = '\0';
+	txt("e.long.test", text);
+	txt("explong.test", "v=spf1 -all exp=e.long.test");
+	explanation("600-char explanation kept whole", "u at explong.test", 600);
+
+	/* exp= target of 316 chars: 255 after one label, 194 after two */
+	char rec[600], *p = rec + sprintf(rec, "v=spf1 -all exp=");
+	for (int i = 0; i < 5; i++, p += 61)
+		sprintf(p, "%c%059d.", 'f' + i, 0);
+	strcpy(p, "e.long.test");
+	txt(strchr(strchr(rec + 16, '.') + 1, '.') + 1, "explained");
+	txt("exptrunc.test", rec);
+	explanation("exp= with a 316-char name", "u at exptrunc.test", 9);
+}
+
+/* ---- empty domain-spec ---- */
+
+static void test_empty_domain(void)
+{
+	static const char *bad[] = { "a:", "a:/24", "a://64", "mx:", "ptr:",
+								 "include:", "exists:", "redirect=", "exp=" };
+	char rec[64], what[64];
+
+	for (size_t i = 0; i < sizeof(bad) / sizeof(*bad); i++) {
+		snprintf(rec, sizeof(rec), "v=spf1 ip4:192.0.2.1 %s -all", bad[i]);
+		snprintf(what, sizeof(what), "empty domain-spec: %s", bad[i]);
+		query(what, "u at nospf.test", "192.0.2.1", rec,
+				SPF_RESULT_PERMERROR, SPF_E_MISSING_OPT);
+	}
+	query("unknown modifier with an empty value", "u at nospf.test", "192.0.2.1",
+			"v=spf1 ip4:192.0.2.1 x= -all", SPF_RESULT_PASS, SPF_E_SUCCESS);
+	query("a with a CIDR and no domain", "u at nospf.test", "192.0.2.9",
+			"v=spf1 a/24 -all", SPF_RESULT_FAIL, SPF_E_SUCCESS);
+}
+
+/* ---- macro truncation ---- */
+
+static void expand(const char *from, const char *helo, const char *macro,
+		const char *want)
+{
+	SPF_request_t	*req = SPF_request_new(srv);
+	SPF_response_t	*resp = SPF_response_new(req);
+	SPF_macro_t		*mac = NULL;
+	char			*buf = NULL, what[128], detail[128];
+	size_t			 buflen = 0;
+	int				 ok;
+
+	SPF_request_set_ipv4_str(req, "192.0.2.1");
+	SPF_request_set_env_from(req, from);
+	SPF_request_set_helo_dom(req, helo);
+	ok = SPF_record_compile_macro(srv, resp, &mac, macro) == SPF_E_SUCCESS
+		&& SPF_record_expand_data(srv, req, resp, SPF_macro_data(mac),
+				mac->macro_len, &buf, &buflen) == SPF_E_SUCCESS
+		&& strcmp(buf, want) == 0;
+	snprintf(what, sizeof(what), "%s with %s / HELO \"%s\" -> \"%s\"",
+			macro, from, helo, want);
+	snprintf(detail, sizeof(detail), "got \"%s\"", buf ? buf : "(null)");
+	check(ok, what, ok ? NULL : detail);
+	free(buf);
+	if (mac)
+		SPF_macro_free(mac);
+	SPF_response_free(resp);
+	SPF_request_free(req);
+}
+
+static void test_macros(void)
+{
+	expand("user at a.b.c", "h.test", "%{l1}", "user");
+	expand("user at a.b.c", "h.test", "%{o1}", "c");
+	expand("user at a.b.c", "h.test", "%{o2}", "b.c");
+	expand("user at a.b.c", "h.test", "%{o5}", "a.b.c");
+	expand("user at a.b.c", "h.test", "%{o2r}", "b.a");
+	expand("-foo at a.test", "h.test", "%{l1-}", "foo");
+	expand("-foo at a.test", "h.test", "%{l2-}", ".foo");
+	expand("-foo at a.test", "h.test", "%{l1r-}", "");
+	expand("-foo at a.test", "h.test", "%{l2r-}", "foo.");
+	expand("user at a.test", "", "%{h1}", "");
+	expand("user at a.test", "", "%{h1r}", "");
+}
+
+/* ---- domain names over 253 chars ---- */
+
+static void test_truncation(void)
+{
+	/* five 60-char labels + "long.test": 314 chars, exactly 253 after
+	 * dropping the first label */
+	char long_name[400] = "", short_name[400], rec[600];
+	const char *tail;
+
+	for (int i = 0; i < 5; i++) {
+		char *p = long_name + strlen(long_name);
+		memset(p, 'a' + i, 60);
+		strcpy(p + 60, ".");
+	}
+	strcat(long_name, "long.test");
+	tail = strchr(long_name, '.') + 1;
+	strcpy(short_name, tail);
+
+	SPF_dns_zone_add_str(zone, short_name, ns_t_a, NETDB_SUCCESS, "192.0.2.1");
+	SPF_dns_zone_add_str(zone, short_name, ns_t_txt, NETDB_SUCCESS, "v=spf1 +all");
+
+	snprintf(rec, sizeof(rec), "v=spf1 a:%s -all", long_name);
+	txt("trunca.test", rec);
+	query("a: with a 314-char name", "u at trunca.test", "192.0.2.1", NULL,
+			SPF_RESULT_PASS, SPF_E_SUCCESS);
+	/* 63.63.63.61: 253 chars, 254 with the root dot, both kept */
+	char max_name[300] = "";
+	for (int i = 0; i < 4; i++) {
+		char *p = max_name + strlen(max_name);
+		memset(p, 'm' + i, i < 3 ? 63 : 61);
+		strcpy(p + (i < 3 ? 63 : 61), i < 3 ? "." : "");
+	}
+	SPF_dns_zone_add_str(zone, max_name, ns_t_a, NETDB_SUCCESS, "192.0.2.1");
+	snprintf(rec, sizeof(rec), "v=spf1 a:%s -all", max_name);
+	txt("truncmax.test", rec);
+	query("a: with a 253-char name", "u at truncmax.test", "192.0.2.1", NULL,
+			SPF_RESULT_PASS, SPF_E_SUCCESS);
+	snprintf(rec, sizeof(rec), "v=spf1 a:%s. -all", max_name);
+	txt("truncmaxdot.test", rec);
+	query("a: with a 253-char name and the root dot", "u at truncmaxdot.test", "192.0.2.1",
+			NULL, SPF_RESULT_PASS, SPF_E_SUCCESS);
+
+	snprintf(rec, sizeof(rec), "v=spf1 exists:%s -all", long_name);
+	txt("truncexists.test", rec);
+	query("exists: with a 314-char name", "u at truncexists.test", "192.0.2.9", NULL,
+			SPF_RESULT_PASS, SPF_E_SUCCESS);
+	snprintf(rec, sizeof(rec), "v=spf1 include:%s -all", long_name);
+	txt("truncinclude.test", rec);
+	query("include: with a 314-char name", "u at truncinclude.test", "192.0.2.9", NULL,
+			SPF_RESULT_PASS, SPF_E_SUCCESS);
+}
+
+/* ---- printing a compiled record ---- */
+
+/* Fill the alignment padding after each modifier string block with
+ * pad, repeated: the printer must not read past a literal. */
+static void fill_padding(SPF_record_t *r, const char *pad)
+{
+	SPF_mod_t *mod = r->mod_first;
+
+	for (int i = 0; i < r->num_mod; i++, mod = SPF_mod_next(mod))
+		for (SPF_data_t *d = SPF_mod_data(mod); d < SPF_mod_end_data(mod);
+				d = SPF_data_next(d)) {
+			if (d->ds.parm_type != PARM_STRING)
+				continue;
+			char *p = SPF_data_str(d) + d->ds.len;
+			for (int j = 0; p < (char *)SPF_data_next(d); j++)
+				*p++ = pad[j % strlen(pad)];
+		}
+}
+
+static char *stringify(const char *rec, const char *pad)
+{
+	SPF_response_t	*resp = SPF_response_new(NULL);
+	SPF_record_t	*r = NULL;
+	char			*buf = NULL;
+	size_t			 len = 0;
+
+	if (SPF_record_compile(srv, resp, &r, rec) == SPF_E_SUCCESS) {
+		fill_padding(r, pad);
+		SPF_record_stringify(r, &buf, &len);
+	}
+	if (r)
+		SPF_record_free(r);
+	SPF_response_free(resp);
+	return buf;
+}
+
+/* rec is in the printer's own form, so it must come back unchanged */
+static void prints_back(const char *what, const char *rec, const char *pad)
+{
+	char	*out = stringify(rec, pad);
+	char	 detail[64];
+	int		 ok = out && strcmp(out, rec) == 0;
+	size_t	 n = out ? strlen(out) : 0;
+
+	snprintf(detail, sizeof(detail), "ends in \"%s\"",
+			out ? out + n - (n < 12 ? n : 12) : "(null)");
+	check(ok, what, ok ? NULL : detail);
+	free(out);
+}
+
+static void test_print(void)
+{
+	char rec[400];
+
+	prints_back("literal ending in %, padding \"20\"", "v=spf1 -all x=%%", "20");
+	prints_back("literal ending in %2, padding \"0\"", "v=spf1 -all x=%%2", "0");
+	/* 254 + '%' fill one 255-char block, "2" starts the next */
+	snprintf(rec, sizeof(rec), "v=spf1 -all x=%0254d%%%%2", 0);
+	prints_back("% at the end of a full string block", rec, "0");
+	snprintf(rec, sizeof(rec), "v=spf1 -all x=%0253d%%%%2", 0);
+	prints_back("%2 at the end of a full string block", rec, "0");
+}
+
+/* ---- DNS cache TTL ---- */
+
+static void test_cache_ttl(void)
+{
+	SPF_dns_server_t	*z = SPF_dns_zone_new(NULL, "ttl", 0);
+	SPF_dns_server_t	*cache;
+	SPF_dns_rr_t		*rr;
+	char				 detail[64];
+
+	SPF_dns_zone_add_str(z, "spf.test", ns_t_spf, NETDB_SUCCESS, "v=spf1 -all");
+	cache = SPF_dns_cache_new(z, "cache", 0, 8);
+	/* the first lookup fills the cache, the second is served from it */
+	SPF_dns_rr_free(SPF_dns_lookup(cache, "spf.test", ns_t_spf, TRUE));
+	rr = SPF_dns_lookup(cache, "spf.test", ns_t_spf, TRUE);
+	snprintf(detail, sizeof(detail), "ttl=%ld", rr ? (long)rr->ttl : -1L);
+	check(rr && rr->ttl == 24 * 60 * 60,
+			"cache keeps the 86400 s TTL of an SPF-type record", detail);
+	SPF_dns_rr_free(rr);
+	SPF_dns_free(cache);	/* frees the zone below it too */
+}
+
+int main(void)
+{
+	SPF_dns_server_t *fake = calloc(1, sizeof(*fake));
+
+	setvbuf(stdout, NULL, _IOLBF, 0);
+
+	zone = SPF_dns_zone_new(NULL, "zone", 0);
+	fake->lookup = fake_lookup;
+	fake->layer_below = zone;
+	fake->name = "fake";
+	srv = SPF_server_new_dns(fake, 0);
+
+	test_limits();
+	test_results();
+	test_dns_limit();
+	test_modifiers();
+	test_empty_domain();
+	test_macros();
+	test_truncation();
+	test_print();
+	test_cache_ttl();
+
+	/* a resolver given to SPF_server_new_dns() and one without a
+	 * destructor are the caller's to free */
+	SPF_server_free(srv);
+	SPF_dns_free(zone);
+	free(fake);
+
+	printf("%d failure(s)\n", failures);
+	return failures != 0;
+}
diff --git a/long-values.patch b/long-values.patch
new file mode 100644
index 0000000..6756ea8
--- /dev/null
+++ b/long-values.patch
@@ -0,0 +1,428 @@
+RFC 7208 sets no length limit on a single literal, mechanism, modifier
+or explanation, but a literal past 255 chars or a value compiling past
+511 bytes made the record a permerror (an explanation: the default
+text). A long literal now continues in further string blocks and the
+compile buffers are sized from the value; only the whole-record limits
+remain. The record printer read two chars past a literal ending in %
+(or %2), which in a heap buffer is uninitialised padding.
+
+--- a/src/libspf2/spf_compile.c
++++ b/src/libspf2/spf_compile.c
+@@ -55,15 +55,15 @@
+ } SPF_domspec_t;
+ 
+ /**
+- * This is greater than any possible total mechanism or modifier.
+- *	 SPF_MAX_MOD_LEN  + SPF_MAX_STR_LEN
+- *	 SPF_MAX_MECH_LEN + SPF_MAX_STR_LEN
++ * Upper bound on the compiled size of a macro-string of src_len chars:
++ * a 4-char %{x} gives a 4-byte variable plus the next string header
++ * (4 bytes + 3 alignment), a literal char at most 3/2 bytes (%-).
+  */
+-#define SPF_RECORD_BUFSIZ	  4096
++#define SPF_MACRO_DATA_MAX(src_len)	(4 * (src_len) + 16)
+ 
+ /**
+- * Limits on a whole compiled record. SPF_MAX_MECH_LEN and
+- * SPF_MAX_MOD_LEN bound a single mechanism or modifier only.
++ * Limits on a whole compiled record; RFC 7208 sets none on a single
++ * mechanism, modifier or literal.
+  */
+ #define SPF_MAX_RECORD_MECH_LEN	16384
+ #define SPF_MAX_RECORD_MOD_LEN	16384
+@@ -71,8 +71,6 @@
+ #define SPF_MAX_NUM_MECH		255
+ #define SPF_MAX_NUM_MOD			255
+ 
+-#define ALIGN_DECL(decl) union { double d; long l; decl } __attribute__((aligned(_ALIGN_SZ))) u
+-#define ALIGNED_DECL(var) u.var
+ 
+ 
+ 
+@@ -473,8 +471,13 @@
+ 			ds_len = 0;												\
+ 		} while(0)
+ 
++/* SPF_data_str_t.len is one byte: a longer literal continues in a new block. */
+ #define SPF_ENSURE_STRING_AVAIL(_len)	do {		\
+-			if (ds_len + _len > ds_avail)			\
++			if (ds_len + (_len) > SPF_MAX_STR_LEN) {	\
++				SPF_FINI_STRING_LITERAL();			\
++				SPF_INIT_STRING_LITERAL(data_avail - *data_used);	\
++			}										\
++			if (ds_len + (_len) > ds_avail)			\
+ 				return SPF_response_add_error_ptr(spf_response,	\
+ 								SPF_E_BIG_STRING, NULL, src,	\
+ 							"String literal fragment too long "	\
+@@ -484,13 +487,6 @@
+ 
+ #define SPF_FINI_STRING_LITERAL()		do { \
+ 			if ( ds_len > 0 ) {										\
+-				if ( ds_len > SPF_MAX_STR_LEN ) {					\
+-					return SPF_response_add_error_ptr(spf_response,		\
+-									SPF_E_BIG_STRING, NULL, src,	\
+-								"String literal too long "			\
+-								"(%d chars, %d max)",				\
+-								ds_len, SPF_MAX_STR_LEN);			\
+-				}													\
+ 				data->ds.len = ds_len;								\
+ 				len = sizeof( *data ) + ds_len;						\
+ 				SPF_ADD_LEN_TO(*data_used, len, data_avail);		\
+@@ -532,6 +528,7 @@
+ 	char				*dst;
+ 	size_t				 ds_avail;
+ 	size_t				 ds_len;
++	size_t				 rest, n;
+ 
+ 	if (spf_server->debug)
+ 		SPF_debugf("Parsing macro starting at %s", src);
+@@ -566,12 +563,19 @@
+ 				SPF_debugf("Adding string literal (%lu): '%*.*s'",
+ 								(unsigned long)len,
+ 								(int)len, (int)len, &src[idx]);
+-			/* XXX Bounds-check here. */
+-			SPF_ENSURE_STRING_AVAIL(len);
+-			memcpy(dst, &src[idx], len);
+-			ds_len += len;
+-			dst += len;
+-			idx += len;
++			/* not len: SPF_FINI_STRING_LITERAL() reuses it */
++			for (rest = len; rest > 0; rest -= n) {
++				n = SPF_MAX_STR_LEN - ds_len;
++				if (n == 0)
++					n = SPF_MAX_STR_LEN;	/* starts a new block */
++				if (n > rest)
++					n = rest;
++				SPF_ENSURE_STRING_AVAIL(n);
++				memcpy(dst, &src[idx], n);
++				ds_len += n;
++				dst += n;
++				idx += n;
++			}
+ 
+ 			/* If len == 0 then we never entered the while(). Thus
+ 			 * if idx == src_len, then len != 0 and we reach this test.
+@@ -840,20 +844,24 @@
+ 				const SPF_mechtype_t *mechtype, int prefix,
+ 				const char **mech_value)
+ {
+-	/* If this buffer is an irregular size, intel gcc does not align
+-	 * it properly, and all hell breaks loose. */
+-ALIGN_DECL(
+-	char				 buf[SPF_RECORD_BUFSIZ];
+-);
+-	SPF_mech_t			*spf_mechanism = (SPF_mech_t *)ALIGNED_DECL(buf);
++	SPF_mech_t			*spf_mechanism;
+ 	SPF_data_t			*data;
+ 	size_t				 data_len;
++	size_t				 data_avail;
+ 	size_t				 len;
+ 	size_t				 src_len;
+ 
+ 	SPF_errcode_t		 err;
+ 
+-	memset(u.buf, 'B', sizeof(u.buf));	/* Poison the buffer. */
++	src_len = strcspn(*mech_value, " ");
++	data_avail = SPF_MACRO_DATA_MAX(src_len);
++	if (data_avail < sizeof(struct in6_addr))
++		data_avail = sizeof(struct in6_addr);
++	spf_mechanism = malloc(sizeof(SPF_mech_t) + data_avail);
++	if (spf_mechanism == NULL)
++		return SPF_response_add_error_ptr(spf_response,
++						SPF_E_NO_MEMORY, NULL, NULL,
++						"Failed to allocate memory for mechanism");
+ 	memset(spf_mechanism, 0, sizeof(SPF_mech_t));
+ 
+ 	if (spf_server->debug)
+@@ -869,8 +877,6 @@
+ 	data = SPF_mech_data(spf_mechanism);
+ 	data_len = 0;
+ 
+-	src_len = strcspn(*mech_value, " ");
+-
+ 	switch (mechtype->mech_type) {
+ 		/* We know the properties of IP4 and IP6. */
+ 			case MECH_IP4:
+@@ -911,7 +917,7 @@
+ 					(*mech_value)++; src_len--;
+ 					err = SPF_c_parse_domainspec(spf_server,
+ 									spf_response,
+-									data, &data_len, SPF_MAX_MECH_LEN,
++									data, &data_len, data_avail,
+ 									*mech_value, src_len,
+ 									SPF_E_BIG_MECH,
+ 									mechtype->has_cidr, FALSE);
+@@ -933,7 +939,7 @@
+ 				else {
+ 					err = SPF_c_parse_domainspec(spf_server,
+ 									spf_response,
+-									data, &data_len, SPF_MAX_MECH_LEN,
++									data, &data_len, data_avail,
+ 									*mech_value, src_len,
+ 									SPF_E_BIG_MECH,
+ 									CIDR_ONLY, FALSE);
+@@ -966,32 +972,35 @@
+ 	len += data_len;
+ 
+ 	/* Copy the thing in. */
+-	if (err == SPF_E_SUCCESS) {
+-		if (spf_record->num_mech >= SPF_MAX_NUM_MECH)
+-			return SPF_response_add_error_ptr(spf_response,
+-							SPF_E_BIG_MECH, NULL, *mech_value,
+-							"Too many mechanisms (%d max)",
+-							SPF_MAX_NUM_MECH);
+-		if (spf_record->mech_len + len > SPF_MAX_RECORD_MECH_LEN)
+-			return SPF_response_add_error_ptr(spf_response,
+-							SPF_E_BIG_MECH, NULL, *mech_value,
+-							"Mechanisms too long (%d bytes max)",
+-							SPF_MAX_RECORD_MECH_LEN);
++	if (err != SPF_E_SUCCESS)
++		;
++	else if (spf_record->num_mech >= SPF_MAX_NUM_MECH)
++		err = SPF_response_add_error_ptr(spf_response,
++						SPF_E_BIG_MECH, NULL, *mech_value,
++						"Too many mechanisms (%d max)",
++						SPF_MAX_NUM_MECH);
++	else if (spf_record->mech_len + len > SPF_MAX_RECORD_MECH_LEN)
++		err = SPF_response_add_error_ptr(spf_response,
++						SPF_E_BIG_MECH, NULL, *mech_value,
++						"Mechanisms too long (%d bytes max)",
++						SPF_MAX_RECORD_MECH_LEN);
++	else if (SPF_c_ensure_capacity((void **)&spf_record->mech_first,
++						&spf_record->mech_size,
++						spf_record->mech_len + len) < 0)
++		err = SPF_response_add_error_ptr(spf_response,
++						SPF_E_NO_MEMORY,
++						NULL, NULL,
++						"Failed to allocate memory for mechanism");
++	else {
+ 		if (mechtype->is_dns_mech)
+ 			spf_record->num_dns_mech++;
+-		if (SPF_c_ensure_capacity((void **)&spf_record->mech_first,
+-							&spf_record->mech_size,
+-							spf_record->mech_len + len) < 0)
+-			return SPF_response_add_error_ptr(spf_response,
+-							SPF_E_NO_MEMORY,
+-							NULL, NULL,
+-							"Failed to allocate memory for mechanism");
+ 		memcpy( (char *)spf_record->mech_first + spf_record->mech_len,
+ 			spf_mechanism,
+ 			len);
+ 		spf_record->mech_len += len;
+ 		spf_record->num_mech++;
+ 	}
++	free(spf_mechanism);
+ 
+ 	*mech_value += src_len;
+ 
+@@ -1005,14 +1014,10 @@
+ 				const char *mod_name, size_t name_len,
+ 				const char **mod_value)
+ {
+-	/* If this buffer is an irregular size, intel gcc does not align
+-	 * it properly, and all hell breaks loose. */
+-ALIGN_DECL(
+-	char				 buf[SPF_RECORD_BUFSIZ];
+-);
+-	SPF_mod_t			*spf_modifier = (SPF_mod_t *)u.buf;
++	SPF_mod_t			*spf_modifier;
+ 	SPF_data_t			*data;
+ 	size_t				 data_len;
++	size_t				 data_avail;
+ 	size_t				 len;
+ 	size_t				 src_len;
+ 
+@@ -1022,64 +1027,67 @@
+ 		SPF_debugf("Adding modifier name=%lu@%s, value=%s",
+ 						(unsigned long)name_len, mod_name, *mod_value);
+ 
+-	memset(u.buf, 'A', sizeof(u.buf));
+-	memset(spf_modifier, 0, sizeof(SPF_mod_t));
++	src_len = strcspn(*mod_value, " ");
+ 
+-	/* Stored modifiers never change the result (redirect= is compiled
+-	 * as a mechanism), so one that does not fit is skipped, not an error. */
+-	if ( name_len > SPF_MAX_MOD_LEN )
+-		return SPF_response_add_warn_ptr(spf_response,
+-						SPF_E_BIG_MOD, NULL, mod_name,
+-						"Modifier name too long (%d chars max), ignored",
+-						SPF_MAX_MOD_LEN);
++	/* Name and data may not fit the record, but the value is still parsed:
++	 * its syntax errors are a permerror (RFC 7208 4.6). */
++	len = _align_sz(sizeof( SPF_mod_t ) + name_len);
++	data_avail = SPF_MACRO_DATA_MAX(src_len);
++	spf_modifier = malloc(len + data_avail);
++	if (spf_modifier == NULL)
++		return SPF_response_add_error_ptr(spf_response,
++						SPF_E_NO_MEMORY, NULL, NULL,
++						"Failed to allocate memory for modifier");
++	memset(spf_modifier, 0, sizeof(SPF_mod_t));
+ 
+ 	spf_modifier->name_len = name_len;
+ 	spf_modifier->data_len = 0;
+ 
+-	/* So that spf_modifier + len == SPF_mod_data(spf_modifier) */
+-	len = _align_sz(sizeof( SPF_mod_t ) + name_len);
+-
+ 	memcpy(SPF_mod_name(spf_modifier), mod_name, name_len);
+ 
+-	data = SPF_mod_data(spf_modifier);
++	/* SPF_mod_data(), without trusting the 16-bit name_len */
++	data = (SPF_data_t *)((char *)spf_modifier + len);
+ 	data_len = 0;
+ 
+-	src_len = strcspn(*mod_value, " ");
+-
+ 	err = SPF_c_parse_macro(spf_server,
+ 					spf_response,
+-					data, &data_len, SPF_MAX_MOD_LEN,
++					data, &data_len, data_avail,
+ 					*mod_value, src_len,
+ 					SPF_E_BIG_MOD,
+ 					TRUE );
+ 	spf_modifier->data_len = data_len;
+ 	len += data_len;
+ 
+-	/* Copy the thing in. */
+-	if (err == SPF_E_SUCCESS) {
+-		if (spf_record->num_mod >= SPF_MAX_NUM_MOD)
+-			return SPF_response_add_warn_ptr(spf_response,
+-							SPF_E_BIG_MOD, NULL, mod_name,
+-							"Too many modifiers (%d max), ignored",
+-							SPF_MAX_NUM_MOD);
+-		if (spf_record->mod_len + len > SPF_MAX_RECORD_MOD_LEN)
+-			return SPF_response_add_warn_ptr(spf_response,
+-							SPF_E_BIG_MOD, NULL, mod_name,
+-							"Modifiers too long (%d bytes max), ignored",
+-							SPF_MAX_RECORD_MOD_LEN);
+-		if (SPF_c_ensure_capacity((void **)&spf_record->mod_first,
+-							&spf_record->mod_size,
+-							spf_record->mod_len + len) < 0)
+-			return SPF_response_add_error_ptr(spf_response,
+-							SPF_E_NO_MEMORY,
+-							NULL, NULL,
+-							"Failed to allocate memory for modifier");
++	/* Copy the thing in. Stored modifiers never change the result
++	 * (redirect= is compiled as a mechanism), so one that does not fit
++	 * is skipped, not an error. */
++	if (err != SPF_E_SUCCESS)
++		;
++	else if (spf_record->num_mod >= SPF_MAX_NUM_MOD)
++		err = SPF_response_add_warn_ptr(spf_response,
++						SPF_E_BIG_MOD, NULL, mod_name,
++						"Too many modifiers (%d max), ignored",
++						SPF_MAX_NUM_MOD);
++	else if (spf_record->mod_len + len > SPF_MAX_RECORD_MOD_LEN)
++		err = SPF_response_add_warn_ptr(spf_response,
++						SPF_E_BIG_MOD, NULL, mod_name,
++						"Modifiers too long (%d bytes max), ignored",
++						SPF_MAX_RECORD_MOD_LEN);
++	else if (SPF_c_ensure_capacity((void **)&spf_record->mod_first,
++						&spf_record->mod_size,
++						spf_record->mod_len + len) < 0)
++		err = SPF_response_add_error_ptr(spf_response,
++						SPF_E_NO_MEMORY,
++						NULL, NULL,
++						"Failed to allocate memory for modifier");
++	else {
+ 		memcpy( (char *)spf_record->mod_first + spf_record->mod_len,
+ 			spf_modifier,
+ 			len);
+ 		spf_record->mod_len += len;
+ 		spf_record->num_mod++;
+ 	}
++	free(spf_modifier);
+ 
+ 	return err;
+ }
+@@ -1096,6 +1104,7 @@
+ 
+ 	int			 found_non_ip;
+ 	int			 found_valid_tld;
++	int			 prev_type;
+ 	
+ 	SPF_mech_t  *mech;
+ 	SPF_data_t  *data;
+@@ -1148,6 +1157,7 @@
+ 		found_valid_tld = FALSE;
+ 		found_non_ip = FALSE;
+ 
++		prev_type = PARM_CIDR;
+ 		for( d = data; d < data_end; d = SPF_data_next( d ) )
+ 		{
+ 			switch( d->dv.parm_type )
+@@ -1163,7 +1173,9 @@
+ 				break;
+ 
+ 			case PARM_STRING:
+-				found_valid_tld = FALSE;
++				/* a long literal continues in the next string block */
++				if (prev_type != PARM_STRING)
++					found_valid_tld = FALSE;
+ 
+ 				s = SPF_data_str( d );
+ 				s_end = s + d->ds.len;
+@@ -1184,6 +1196,7 @@
+ 			
+ 				break;
+ 			}
++			prev_type = d->dv.parm_type;
+ 		}
+ 
+ 		if ( !found_valid_tld || !found_non_ip ) {
+@@ -1571,30 +1584,27 @@
+ 								SPF_macro_t **spf_macrop,
+ 								const char *record)
+ {
+-ALIGN_DECL(
+-	char			 buf[sizeof(SPF_macro_t) + SPF_MAX_MOD_LEN];
+-);
+-	SPF_macro_t		*spf_macro = (SPF_macro_t *)ALIGNED_DECL(buf);
++	SPF_macro_t		*spf_macro;
+ 	SPF_data_t		*data;
+ 	SPF_errcode_t	 err;
+-	size_t			 size;
+-	
++	size_t			 src_len = strlen(record);
++	size_t			 data_avail = SPF_MACRO_DATA_MAX(src_len);
++
++	spf_macro = (SPF_macro_t *)malloc(sizeof(SPF_macro_t) + data_avail);
++	if (!spf_macro)
++		return SPF_E_NO_MEMORY;
+ 	data = SPF_macro_data(spf_macro);
+ 	spf_macro->macro_len = 0;
+ 
+ 	err = SPF_c_parse_macro(spf_server, spf_response,
+-					data, &spf_macro->macro_len, SPF_MAX_MOD_LEN,
+-					record, strlen(record),
++					data, &spf_macro->macro_len, data_avail,
++					record, src_len,
+ 					SPF_E_BIG_MOD, TRUE);
+-	if (err != SPF_E_SUCCESS)
++	if (err != SPF_E_SUCCESS) {
++		free(spf_macro);
+ 		return err;
+-
+-	/* XXX TODO: Tidy this up? */
+-	size = sizeof(SPF_macro_t) + spf_macro->macro_len;
+-	*spf_macrop = (SPF_macro_t *)malloc(size);
+-	if (!*spf_macrop)
+-		return SPF_E_NO_MEMORY;
+-	memcpy(*spf_macrop, ALIGNED_DECL(buf), size);
++	}
++	*spf_macrop = spf_macro;
+ 
+ 	return SPF_E_SUCCESS;
+ }
+--- a/src/libspf2/spf_id2str.c
++++ b/src/libspf2/spf_id2str.c
+@@ -95,7 +95,8 @@
+ 				else if (*s == '%') {
+ 					*p++ = '%';
+ 					s++;
+-					if (s[0] == '2' && s[1] == '0') {
++					/* only within this literal */
++					if (s_end - s >= 2 && s[0] == '2' && s[1] == '0') {
+ 						*p++ = '-';
+ 						s += 2;
+ 					}
diff --git a/macro-truncate.patch b/macro-truncate.patch
new file mode 100644
index 0000000..1455555
--- /dev/null
+++ b/macro-truncate.patch
@@ -0,0 +1,31 @@
+%{l1} or %{d3} on a value with fewer parts than requested dropped its
+first character ("user" -> "ser"); RFC 7208 7.3 keeps the whole value.
+A leading delimiter starts an empty part ("-foo": %{l1-} -> "foo",
+%{l2-} -> ".foo"), and an empty value stays empty.
+Based on https://github.com/shevek/libspf2/pull/43, which still drops
+the character when 0 < delimiters < requested.
+
+--- a/src/libspf2/spf_expand.c
++++ b/src/libspf2/spf_expand.c
+@@ -344,17 +344,16 @@
+ 
+ 		/* truncate, from the right hand side. */
+ 		if (d->dv.num_rhs > 0) {
++			/* Keep the rightmost num_rhs parts; a value with fewer
++			 * parts is kept whole, a leading '.' starts an empty part. */
+ 			p_read_end = munged_var + len;		/* const, at '\0' */
+-			p_write = munged_var + len - 1;
++			p_write = munged_var + len;
+ 			num_found = 0;
+ 			while (p_write > munged_var) {
+-				if (*p_write == '.')
+-					num_found++;
+-				if (num_found == d->dv.num_rhs)
++				if (p_write[-1] == '.' && ++num_found == d->dv.num_rhs)
+ 					break;
+ 				p_write--;
+ 			}
+-			p_write++;		/* Move to just after the '.' */
+ 			/* This moves the '\0' as well. */
+ 			len = p_read_end - p_write;
+ 			memmove(munged_var, p_write, len + 1);
diff --git a/malformed-domain.patch b/malformed-domain.patch
new file mode 100644
index 0000000..7bf0699
--- /dev/null
+++ b/malformed-domain.patch
@@ -0,0 +1,50 @@
+RFC 7208 4.3: check_host() returns none for a malformed domain (an empty
+label, a label over 63 chars) without a lookup. libspf2 queried it, the
+resolver failed with NO_RECOVERY, and the sender got temperror, deferring
+mail that can never pass; an include of such a domain is now a permerror.
+
+--- a/src/libspf2/spf_server.c
++++ b/src/libspf2/spf_server.c
+@@ -312,6 +312,28 @@
+ 	return err;
+ }
+ 
++/* RFC 7208 4.3: an empty label not at the end, a label over 63 chars or
++ * a name over 253 chars; the resolver would fail it as a DNS error */
++static int
++SPF_domain_malformed(const char *domain)
++{
++	const char	*p, *dot;
++	size_t		 len = strlen(domain);
++
++	if (len > 0 && domain[len - 1] == '.')
++		len--;
++	if (len > 253)
++		return 1;
++	for (p = domain; p < domain + len; p = dot + 1) {
++		dot = memchr(p, '.', domain + len - p);
++		if (dot == NULL)
++			dot = domain + len;
++		if (dot == p || dot - p > 63)
++			return 1;
++	}
++	return 0;
++}
++
+ SPF_errcode_t
+ SPF_server_get_record(SPF_server_t *spf_server,
+ 				SPF_request_t *spf_request,
+@@ -339,6 +361,13 @@
+ 
+ 	*spf_recordp = NULL;
+ 
++	if (SPF_domain_malformed(domain)) {
++		spf_response->result = SPF_RESULT_NONE;
++		spf_response->reason = SPF_REASON_FAILURE;
++		return SPF_response_add_error(spf_response, SPF_E_NOT_SPF,
++				"Malformed domain name '%s'.", domain);
++	}
++
+ 	resolver = spf_server->resolver;
+ 
+ 	if (resolver->get_spf)
diff --git a/query-record-uaf.patch b/query-record-uaf.patch
new file mode 100644
index 0000000..5c7b584
--- /dev/null
+++ b/query-record-uaf.patch
@@ -0,0 +1,23 @@
+From 8b50e5cef36fc7fbc3c8808168e51cc33a3cc940 Mon Sep 17 00:00:00 2001
+From: bdijkstra82 <boudewijn at indes.com>
+Date: Wed, 30 Mar 2016 21:47:46 +0200
+Subject: [PATCH] fix use-after-free
+
+Not sure what the intention is here, but in no case should
+spf_record_exp point to a freed object. (Fixes crash on OpenBSD 5.9.)
+---
+ src/libspf2/spf_request.c | 1 +
+ 1 file changed, 1 insertion(+)
+
+diff --git a/src/libspf2/spf_request.c b/src/libspf2/spf_request.c
+index c310a5a..8a73275 100644
+--- a/src/libspf2/spf_request.c
++++ b/src/libspf2/spf_request.c
+@@ -259,6 +259,7 @@ SPF_request_query_record(SPF_request_t *spf_request,
+ 	err = SPF_record_interpret(spf_record,
+ 					spf_request, spf_response, 0);
+ 	SPF_record_free(spf_record);
++	spf_response->spf_record_exp = NULL;
+ 
+ 	return err;
+ }
diff --git a/record-mech-len.patch b/record-mech-len.patch
new file mode 100644
index 0000000..66c5ffb
--- /dev/null
+++ b/record-mech-len.patch
@@ -0,0 +1,97 @@
+SPF_MAX_MECH_LEN/SPF_MAX_MOD_LEN (511) were checked against the whole
+compiled record, so mechanisms past ~511 bytes (64 ip4) were silently
+dropped, -all included, and compilation reported no error. Mechanisms
+past the new limits are a permerror; modifiers past them are skipped
+with a warning, as RFC 7208 6 requires unknown ones to be ignored.
+https://github.com/shevek/libspf2/issues/21
+https://github.com/shevek/libspf2/issues/48
+https://github.com/shevek/libspf2/issues/60
+
+--- a/src/libspf2/spf_compile.c
++++ b/src/libspf2/spf_compile.c
+@@ -61,6 +61,16 @@
+  */
+ #define SPF_RECORD_BUFSIZ	  4096
+ 
++/**
++ * Limits on a whole compiled record. SPF_MAX_MECH_LEN and
++ * SPF_MAX_MOD_LEN bound a single mechanism or modifier only.
++ */
++#define SPF_MAX_RECORD_MECH_LEN	16384
++#define SPF_MAX_RECORD_MOD_LEN	16384
++/* SPF_record_t.num_mech and num_mod are unsigned char. */
++#define SPF_MAX_NUM_MECH		255
++#define SPF_MAX_NUM_MOD			255
++
+ #define ALIGN_DECL(decl) union { double d; long l; decl } __attribute__((aligned(_ALIGN_SZ))) u
+ #define ALIGNED_DECL(var) u.var
+ 
+@@ -856,9 +866,6 @@
+ 
+ 	len = sizeof( SPF_mech_t );
+ 
+-	if ( spf_record->mech_len + len > SPF_MAX_MECH_LEN )
+-		return SPF_E_BIG_MECH;
+-
+ 	data = SPF_mech_data(spf_mechanism);
+ 	data_len = 0;
+ 
+@@ -960,6 +967,16 @@
+ 
+ 	/* Copy the thing in. */
+ 	if (err == SPF_E_SUCCESS) {
++		if (spf_record->num_mech >= SPF_MAX_NUM_MECH)
++			return SPF_response_add_error_ptr(spf_response,
++							SPF_E_BIG_MECH, NULL, *mech_value,
++							"Too many mechanisms (%d max)",
++							SPF_MAX_NUM_MECH);
++		if (spf_record->mech_len + len > SPF_MAX_RECORD_MECH_LEN)
++			return SPF_response_add_error_ptr(spf_response,
++							SPF_E_BIG_MECH, NULL, *mech_value,
++							"Mechanisms too long (%d bytes max)",
++							SPF_MAX_RECORD_MECH_LEN);
+ 		if (mechtype->is_dns_mech)
+ 			spf_record->num_dns_mech++;
+ 		if (SPF_c_ensure_capacity((void **)&spf_record->mech_first,
+@@ -1008,8 +1025,13 @@
+ 	memset(u.buf, 'A', sizeof(u.buf));
+ 	memset(spf_modifier, 0, sizeof(SPF_mod_t));
+ 
++	/* Stored modifiers never change the result (redirect= is compiled
++	 * as a mechanism), so one that does not fit is skipped, not an error. */
+ 	if ( name_len > SPF_MAX_MOD_LEN )
+-		return SPF_E_BIG_MOD;
++		return SPF_response_add_warn_ptr(spf_response,
++						SPF_E_BIG_MOD, NULL, mod_name,
++						"Modifier name too long (%d chars max), ignored",
++						SPF_MAX_MOD_LEN);
+ 
+ 	spf_modifier->name_len = name_len;
+ 	spf_modifier->data_len = 0;
+@@ -1017,9 +1039,6 @@
+ 	/* So that spf_modifier + len == SPF_mod_data(spf_modifier) */
+ 	len = _align_sz(sizeof( SPF_mod_t ) + name_len);
+ 
+-	if ( spf_record->mod_len + len > SPF_MAX_MOD_LEN )
+-		return SPF_E_BIG_MOD;
+-
+ 	memcpy(SPF_mod_name(spf_modifier), mod_name, name_len);
+ 
+ 	data = SPF_mod_data(spf_modifier);
+@@ -1038,6 +1057,16 @@
+ 
+ 	/* Copy the thing in. */
+ 	if (err == SPF_E_SUCCESS) {
++		if (spf_record->num_mod >= SPF_MAX_NUM_MOD)
++			return SPF_response_add_warn_ptr(spf_response,
++							SPF_E_BIG_MOD, NULL, mod_name,
++							"Too many modifiers (%d max), ignored",
++							SPF_MAX_NUM_MOD);
++		if (spf_record->mod_len + len > SPF_MAX_RECORD_MOD_LEN)
++			return SPF_response_add_warn_ptr(spf_response,
++							SPF_E_BIG_MOD, NULL, mod_name,
++							"Modifiers too long (%d bytes max), ignored",
++							SPF_MAX_RECORD_MOD_LEN);
+ 		if (SPF_c_ensure_capacity((void **)&spf_record->mod_first,
+ 							&spf_record->mod_size,
+ 							spf_record->mod_len + len) < 0)
diff --git a/redirect-last.patch b/redirect-last.patch
new file mode 100644
index 0000000..59bfe8b
--- /dev/null
+++ b/redirect-last.patch
@@ -0,0 +1,91 @@
+From 23e0dcfb4d6a348ee68c5822b3a4f06e82258839 Mon Sep 17 00:00:00 2001
+From: Ilya Pronin <iopronin at yandex.ru>
+Date: Thu, 26 Nov 2015 16:58:24 +0300
+Subject: [PATCH] Fix "redirect" modifier handling
+
+Add it to the end of the mechanisms list so it will be taken into account only if all other mechanisms failed to match.
+
+PLD: refreshed; redirect_prefix initialized (gcc -Wmaybe-uninitialized);
+a second redirect= is an error, RFC 7208 6 requires permerror.
+---
+
+--- a/src/libspf2/spf_compile.c
++++ b/src/libspf2/spf_compile.c
+@@ -1231,6 +1231,10 @@
+ 	const char			*p;
+ 	int					 i;
+ 
++	const SPF_mechtype_t*redirect_mechtype = NULL;
++	int					 redirect_prefix = PREFIX_UNKNOWN;
++	const char			*redirect_val_start;
++
+ 
+ 	/*
+ 	 * make sure we were passed valid data to work with
+@@ -1415,8 +1419,6 @@
+ 				continue;
+ 			}
+ #endif
+-			/* FIXME  the redirect mechanism needs to be moved to
+-			 * the very end */
+ 			else if ( STREQ_SIZEOF_N(name_start, "redirect", name_len) )
+ 				mechtype = SPF_mechtype_find(MECH_REDIRECT);
+ 			else
+@@ -1436,16 +1438,30 @@
+ 								"a recognised mechanism");
+ 			}
+ 
+-			if (spf_server->debug)
+-				SPF_debugf("Adding mechanism type %d",
+-								(int)mechtype->mech_type);
+-
+ 			val_start = p;
+-			err = SPF_c_mech_add(spf_server,
+-							spf_record, spf_response,
+-							mechtype, prefix, &val_start);
+-			if (err == SPF_E_NO_MEMORY)
+-				return err;
++			if (mechtype->mech_type == MECH_REDIRECT) {
++				/* Syntactically "redirect" modifier can appear anywhere in the
++				 * record. But it must be taken into account only if all other
++				 * mechanisms failed to match. So we postpone its adding. */
++				if (redirect_mechtype == NULL) {
++					redirect_mechtype = mechtype;
++					redirect_prefix = prefix;
++					redirect_val_start = val_start;
++				}
++				else	/* RFC 7208 6: at most once, else permerror */
++					SPF_response_add_error_ptr(spf_response, SPF_E_SYNTAX,
++									NULL, name_start,
++									"Multiple redirect= modifiers");
++			}
++			else {
++				if (spf_server->debug)
++					SPF_debugf("Adding mechanism type %d",
++									(int)mechtype->mech_type);
++				err = SPF_c_mech_add(spf_server, spf_record, spf_response,
++								mechtype, prefix, &val_start);
++				if (err == SPF_E_NO_MEMORY)
++					return err;
++			}
+ 			/* XXX Else do nothing. Continue for the next error. */
+ 			/* We shouldn't have to worry about the child function
+ 			 * updating the pointer. So we just use our 'well known'
+@@ -1501,6 +1517,17 @@
+ 		}
+ 	}
+ 	
++	/* If there was a "redirect" modifier add it to the end. */
++	if (redirect_mechtype) {
++		if (spf_server->debug)
++				SPF_debugf("Adding mechanism type %d",
++								(int)redirect_mechtype->mech_type);
++		err = SPF_c_mech_add(spf_server, spf_record, spf_response,
++						redirect_mechtype, redirect_prefix,
++						&redirect_val_start);
++		if (err == SPF_E_NO_MEMORY)
++			return err;
++	}
+ 
+ 	/*
+ 	 * check for common mistakes
diff --git a/rfc-error-results.patch b/rfc-error-results.patch
new file mode 100644
index 0000000..cfed5e9
--- /dev/null
+++ b/rfc-error-results.patch
@@ -0,0 +1,71 @@
+RFC 7208 results for errors in the checked domain's own record lookup.
+
+A record that does not compile (syntax error, too many mechanisms)
+must give permerror (RFC 7208 4.6); libspf2 left the result unset,
+so SPF_response_result() returned SPF_RESULT_INVALID, the response
+error code stayed SPF_E_SUCCESS and Received-SPF said "(invalid)".
+Applies to SPF_request_query_mailfrom(), _fallback() and _rcptto();
+the same record behind include:/redirect= already gave permerror.
+The response now also carries the compile error code.
+
+DNS errors other than NXDOMAIN must give temperror (RFC 7208 4.4):
+NO_RECOVERY gave permerror and unknown h_errno values gave
+"(invalid)"; behind include:/redirect= both already gave temperror.
+A successful lookup with no TXT records is none (RFC 7208 4.5).
+
+--- a/src/libspf2/spf_request.c
++++ b/src/libspf2/spf_request.c
+@@ -246,7 +246,14 @@
+ 	if (err != SPF_E_SUCCESS) {
+ 		if (spf_record)
+ 			SPF_record_free(spf_record);
+-		SPF_i_done(spf_response, spf_response->result, spf_response->reason, spf_response->err);
++		/* Lookup failures set their own result; an unset one means
++		 * the record did not compile (RFC 7208 4.6: permerror). */
++		if (spf_response->result == SPF_RESULT_INVALID) {
++			spf_response->result = err == SPF_E_NO_MEMORY
++					? SPF_RESULT_TEMPERROR : SPF_RESULT_PERMERROR;
++			spf_response->reason = SPF_REASON_FAILURE;
++		}
++		SPF_i_done(spf_response, spf_response->result, spf_response->reason, err);
+ 		return err;
+ 	}
+ 	/* Now, in theory, SPF_response_errors(spf_response) == 0 */
+--- a/src/libspf2/spf_server.c
++++ b/src/libspf2/spf_server.c
+@@ -401,7 +401,7 @@
+ 				rr_type = ns_t_txt;
+ 				goto retry;
+ 			}
+-			spf_response->result = SPF_RESULT_PERMERROR;
++			spf_response->result = SPF_RESULT_TEMPERROR;
+ 			spf_response->reason = SPF_REASON_FAILURE;
+ 			return SPF_response_add_error(spf_response, SPF_E_DNS_ERROR,
+ 					"Unrecoverable DNS failure for '%s'.", domain);
+@@ -421,6 +421,8 @@
+ 				rr_type = ns_t_txt;
+ 				goto retry;
+ 			}
++			spf_response->result = SPF_RESULT_TEMPERROR;
++			spf_response->reason = SPF_REASON_FAILURE;
+ 			return SPF_response_add_error(spf_response, SPF_E_DNS_ERROR,
+ 					"Unknown DNS failure for '%s': %d.",
+ 					domain, herrno);
+@@ -433,6 +435,8 @@
+ 			rr_type = ns_t_txt;
+ 			goto retry;
+ 		}
++		spf_response->result = SPF_RESULT_NONE;
++		spf_response->reason = SPF_REASON_FAILURE;
+ 		return SPF_response_add_error(spf_response, SPF_E_NOT_SPF,
+ 				"No TXT records returned from DNS lookup for '%s'",
+ 				domain);
+@@ -490,7 +494,7 @@
+ 
+ 	/* FIXME: support multiple versions */
+ 	if (err != SPF_E_SUCCESS)
+-		return SPF_response_add_error(spf_response, SPF_E_NOT_SPF,
++		return SPF_response_add_error(spf_response, err,
+ 				"Failed to compile SPF record for '%s'", domain);
+ 
+ 	return SPF_E_SUCCESS;
================================================================

---- gitweb:

http://git.pld-linux.org/gitweb.cgi/packages/libspf2.git/commitdiff/be76952d3f72cf6dc88f63b5ac59334c418f7aaf



More information about the pld-cvs-commit mailing list