xref: /freebsd/contrib/unbound/smallapp/unbound-anchor.c (revision f4b37ed0f8b307b1f3f0f630ca725d68f1dff30d)
1 /*
2  * unbound-anchor.c - update the root anchor if necessary.
3  *
4  * Copyright (c) 2010, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file checks to see that the current 5011 keys work to prime the
40  * current root anchor.  If not a certificate is used to update the anchor.
41  *
42  * This is a concept solution for distribution of the DNSSEC root
43  * trust anchor.  It is a small tool, called "unbound-anchor", that
44  * runs before the main validator starts.  I.e. in the init script:
45  * unbound-anchor; unbound.  Thus it is meant to run at system boot time.
46  *
47  * Management-Abstract:
48  *    * first run: fill root.key file with hardcoded DS record.
49  *    * mostly: use RFC5011 tracking, quick . DNSKEY UDP query.
50  *    * failover: use builtin certificate, do https and update.
51  * Special considerations:
52  *    * 30-days RFC5011 timer saves a lot of https traffic.
53  *    * DNSKEY probe must be NOERROR, saves a lot of https traffic.
54  *    * fail if clock before sign date of the root, if cert expired.
55  *    * if the root goes back to unsigned, deals with it.
56  *
57  * It has hardcoded the root DS anchors and the ICANN CA root certificate.
58  * It allows with options to override those.  It also takes root-hints (it
59  * has to do a DNS resolve), and also has hardcoded defaults for those.
60  *
61  * Once it starts, just before the validator starts, it quickly checks if
62  * the root anchor file needs to be updated.  First it tries to use
63  * RFC5011-tracking of the root key.  If that fails (and for 30-days since
64  * last successful probe), then it attempts to update using the
65  * certificate.  So most of the time, the RFC5011 tracking will work fine,
66  * and within a couple milliseconds, the main daemon can start.  It will
67  * have only probed the . DNSKEY, not done expensive https transfers on the
68  * root infrastructure.
69  *
70  * If there is no root key in the root.key file, it bootstraps the
71  * RFC5011-tracking with its builtin DS anchors; if that fails it
72  * bootstraps the RFC5011-tracking using the certificate.  (again to avoid
73  * https, and it is also faster).
74  *
75  * It uses the XML file by converting it to DS records and writing that to the
76  * key file.  Unbound can detect that the 'special comments' are gone, and
77  * the file contains a list of normal DNSKEY/DS records, and uses that to
78  * bootstrap 5011 (the KSK is made VALID).
79  *
80  * The certificate update is done by fetching root-anchors.xml and
81  * root-anchors.p7s via SSL.  The HTTPS certificate can be logged but is
82  * not validated (https for channel security; the security comes from the
83  * certificate).  The 'data.iana.org' domain name A and AAAA are resolved
84  * without DNSSEC.  It tries a random IP until the transfer succeeds.  It
85  * then checks the p7s signature.
86  *
87  * On any failure, it leaves the root key file untouched.  The main
88  * validator has to cope with it, it cannot fix things (So a failure does
89  * not go 'without DNSSEC', no downgrade).  If it used its builtin stuff or
90  * did the https, it exits with an exit code, so that this can trigger the
91  * init script to log the event and potentially alert the operator that can
92  * do a manual check.
93  *
94  * The date is also checked.  Before 2010-07-15 is a failure (root not
95  * signed yet; avoids attacks on system clock).  The
96  * last-successful-RFC5011-probe (if available) has to be more than 30 days
97  * in the past (otherwise, RFC5011 should have worked).  This keeps
98  * unneccesary https traffic down.  If the main certificate is expired, it
99  * fails.
100  *
101  * The dates on the keys in the xml are checked (uses the libexpat xml
102  * parser), only the valid ones are used to re-enstate RFC5011 tracking.
103  * If 0 keys are valid, the zone has gone to insecure (a special marker is
104  * written in the keyfile that tells the main validator daemon the zone is
105  * insecure).
106  *
107  * Only the root ICANN CA is shipped, not the intermediate ones.  The
108  * intermediate CAs are included in the p7s file that was downloaded.  (the
109  * root cert is valid to 2028 and the intermediate to 2014, today).
110  *
111  * Obviously, the tool also has options so the operator can provide a new
112  * keyfile, a new certificate and new URLs, and fresh root hints.  By
113  * default it logs nothing on failure and success; it 'just works'.
114  *
115  */
116 
117 #include "config.h"
118 #include "libunbound/unbound.h"
119 #include "ldns/rrdef.h"
120 #include <expat.h>
121 #ifndef HAVE_EXPAT_H
122 #error "need libexpat to parse root-anchors.xml file."
123 #endif
124 #ifdef HAVE_GETOPT_H
125 #include <getopt.h>
126 #endif
127 #ifdef HAVE_OPENSSL_SSL_H
128 #include <openssl/ssl.h>
129 #endif
130 #ifdef HAVE_OPENSSL_ERR_H
131 #include <openssl/err.h>
132 #endif
133 #ifdef HAVE_OPENSSL_RAND_H
134 #include <openssl/rand.h>
135 #endif
136 #include <openssl/x509.h>
137 #include <openssl/x509v3.h>
138 #include <openssl/pem.h>
139 
140 /** name of server in URL to fetch HTTPS from */
141 #define URLNAME "data.iana.org"
142 /** path on HTTPS server to xml file */
143 #define XMLNAME "root-anchors/root-anchors.xml"
144 /** path on HTTPS server to p7s file */
145 #define P7SNAME "root-anchors/root-anchors.p7s"
146 /** name of the signer of the certificate */
147 #define P7SIGNER "dnssec@iana.org"
148 /** port number for https access */
149 #define HTTPS_PORT 443
150 
151 #ifdef USE_WINSOCK
152 /* sneakily reuse the the wsa_strerror function, on windows */
153 char* wsa_strerror(int err);
154 #endif
155 
156 /** verbosity for this application */
157 static int verb = 0;
158 
159 /** list of IP addresses */
160 struct ip_list {
161 	/** next in list */
162 	struct ip_list* next;
163 	/** length of addr */
164 	socklen_t len;
165 	/** address ready to connect to */
166 	struct sockaddr_storage addr;
167 	/** has the address been used */
168 	int used;
169 };
170 
171 /** Give unbound-anchor usage, and exit (1). */
172 static void
173 usage()
174 {
175 	printf("Usage:	unbound-anchor [opts]\n");
176 	printf("	Setup or update root anchor. "
177 		"Most options have defaults.\n");
178 	printf("	Run this program before you start the validator.\n");
179 	printf("\n");
180 	printf("	The anchor and cert have default builtin content\n");
181 	printf("	if the file does not exist or is empty.\n");
182 	printf("\n");
183 	printf("-a file		root key file, default %s\n", ROOT_ANCHOR_FILE);
184 	printf("		The key is input and output for this tool.\n");
185 	printf("-c file		cert file, default %s\n", ROOT_CERT_FILE);
186 	printf("-l		list builtin key and cert on stdout\n");
187 	printf("-u name		server in https url, default %s\n", URLNAME);
188 	printf("-x path		pathname to xml in url, default %s\n", XMLNAME);
189 	printf("-s path		pathname to p7s in url, default %s\n", P7SNAME);
190 	printf("-n name		signer's subject emailAddress, default %s\n", P7SIGNER);
191 	printf("-4		work using IPv4 only\n");
192 	printf("-6		work using IPv6 only\n");
193 	printf("-f resolv.conf	use given resolv.conf to resolve -u name\n");
194 	printf("-r root.hints	use given root.hints to resolve -u name\n"
195 		"		builtin root hints are used by default\n");
196 	printf("-v		more verbose\n");
197 	printf("-C conf		debug, read config\n");
198 	printf("-P port		use port for https connect, default 443\n");
199 	printf("-F 		debug, force update with cert\n");
200 	printf("-h		show this usage help\n");
201 	printf("Version %s\n", PACKAGE_VERSION);
202 	printf("BSD licensed, see LICENSE in source package for details.\n");
203 	printf("Report bugs to %s\n", PACKAGE_BUGREPORT);
204 	exit(1);
205 }
206 
207 /** return the built in root update certificate */
208 static const char*
209 get_builtin_cert(void)
210 {
211 	return
212 /* The ICANN CA fetched at 24 Sep 2010.  Valid to 2028 */
213 "-----BEGIN CERTIFICATE-----\n"
214 "MIIDdzCCAl+gAwIBAgIBATANBgkqhkiG9w0BAQsFADBdMQ4wDAYDVQQKEwVJQ0FO\n"
215 "TjEmMCQGA1UECxMdSUNBTk4gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxFjAUBgNV\n"
216 "BAMTDUlDQU5OIFJvb3QgQ0ExCzAJBgNVBAYTAlVTMB4XDTA5MTIyMzA0MTkxMloX\n"
217 "DTI5MTIxODA0MTkxMlowXTEOMAwGA1UEChMFSUNBTk4xJjAkBgNVBAsTHUlDQU5O\n"
218 "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRYwFAYDVQQDEw1JQ0FOTiBSb290IENB\n"
219 "MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKDb\n"
220 "cLhPNNqc1NB+u+oVvOnJESofYS9qub0/PXagmgr37pNublVThIzyLPGCJ8gPms9S\n"
221 "G1TaKNIsMI7d+5IgMy3WyPEOECGIcfqEIktdR1YWfJufXcMReZwU4v/AdKzdOdfg\n"
222 "ONiwc6r70duEr1IiqPbVm5T05l1e6D+HkAvHGnf1LtOPGs4CHQdpIUcy2kauAEy2\n"
223 "paKcOcHASvbTHK7TbbvHGPB+7faAztABLoneErruEcumetcNfPMIjXKdv1V1E3C7\n"
224 "MSJKy+jAqqQJqjZoQGB0necZgUMiUv7JK1IPQRM2CXJllcyJrm9WFxY0c1KjBO29\n"
225 "iIKK69fcglKcBuFShUECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8B\n"
226 "Af8EBAMCAf4wHQYDVR0OBBYEFLpS6UmDJIZSL8eZzfyNa2kITcBQMA0GCSqGSIb3\n"
227 "DQEBCwUAA4IBAQAP8emCogqHny2UYFqywEuhLys7R9UKmYY4suzGO4nkbgfPFMfH\n"
228 "6M+Zj6owwxlwueZt1j/IaCayoKU3QsrYYoDRolpILh+FPwx7wseUEV8ZKpWsoDoD\n"
229 "2JFbLg2cfB8u/OlE4RYmcxxFSmXBg0yQ8/IoQt/bxOcEEhhiQ168H2yE5rxJMt9h\n"
230 "15nu5JBSewrCkYqYYmaxyOC3WrVGfHZxVI7MpIFcGdvSb2a1uyuua8l0BKgk3ujF\n"
231 "0/wsHNeP22qNyVO+XVBzrM8fk8BSUFuiT/6tZTYXRtEt5aKQZgXbKU5dUF3jT9qg\n"
232 "j/Br5BZw3X/zd325TvnswzMC1+ljLzHnQGGk\n"
233 "-----END CERTIFICATE-----\n"
234 		;
235 }
236 
237 /** return the built in root DS trust anchor */
238 static const char*
239 get_builtin_ds(void)
240 {
241 	return
242 ". IN DS 19036 8 2 49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5\n";
243 }
244 
245 /** print hex data */
246 static void
247 print_data(const char* msg, const char* data, int len)
248 {
249 	int i;
250 	printf("%s: ", msg);
251 	for(i=0; i<len; i++) {
252 		printf(" %2.2x", (unsigned char)data[i]);
253 	}
254 	printf("\n");
255 }
256 
257 /** print ub context creation error and exit */
258 static void
259 ub_ctx_error_exit(struct ub_ctx* ctx, const char* str, const char* str2)
260 {
261 	ub_ctx_delete(ctx);
262 	if(str && str2 && verb) printf("%s: %s\n", str, str2);
263 	if(verb) printf("error: could not create unbound resolver context\n");
264 	exit(0);
265 }
266 
267 /**
268  * Create a new unbound context with the commandline settings applied
269  */
270 static struct ub_ctx*
271 create_unbound_context(const char* res_conf, const char* root_hints,
272 	const char* debugconf, int ip4only, int ip6only)
273 {
274 	int r;
275 	struct ub_ctx* ctx = ub_ctx_create();
276 	if(!ctx) {
277 		if(verb) printf("out of memory\n");
278 		exit(0);
279 	}
280 	/* do not waste time and network traffic to fetch extra nameservers */
281 	r = ub_ctx_set_option(ctx, "target-fetch-policy:", "0 0 0 0 0");
282 	if(r && verb) printf("ctx targetfetchpolicy: %s\n", ub_strerror(r));
283 	/* read config file first, so its settings can be overridden */
284 	if(debugconf) {
285 		r = ub_ctx_config(ctx, debugconf);
286 		if(r) ub_ctx_error_exit(ctx, debugconf, ub_strerror(r));
287 	}
288 	if(res_conf) {
289 		r = ub_ctx_resolvconf(ctx, res_conf);
290 		if(r) ub_ctx_error_exit(ctx, res_conf, ub_strerror(r));
291 	}
292 	if(root_hints) {
293 		r = ub_ctx_set_option(ctx, "root-hints:", root_hints);
294 		if(r) ub_ctx_error_exit(ctx, root_hints, ub_strerror(r));
295 	}
296 	if(ip4only) {
297 		r = ub_ctx_set_option(ctx, "do-ip6:", "no");
298 		if(r) ub_ctx_error_exit(ctx, "ip4only", ub_strerror(r));
299 	}
300 	if(ip6only) {
301 		r = ub_ctx_set_option(ctx, "do-ip4:", "no");
302 		if(r) ub_ctx_error_exit(ctx, "ip6only", ub_strerror(r));
303 	}
304 	return ctx;
305 }
306 
307 /** printout certificate in detail */
308 static void
309 verb_cert(const char* msg, X509* x)
310 {
311 	if(verb == 0 || verb == 1) return;
312 	if(verb == 2) {
313 		if(msg) printf("%s\n", msg);
314 		X509_print_ex_fp(stdout, x, 0, (unsigned long)-1
315 			^(X509_FLAG_NO_SUBJECT
316 			|X509_FLAG_NO_ISSUER|X509_FLAG_NO_VALIDITY));
317 		return;
318 	}
319 	if(msg) printf("%s\n", msg);
320 	X509_print_fp(stdout, x);
321 }
322 
323 /** printout certificates in detail */
324 static void
325 verb_certs(const char* msg, STACK_OF(X509)* sk)
326 {
327 	int i, num = sk_X509_num(sk);
328 	if(verb == 0 || verb == 1) return;
329 	for(i=0; i<num; i++) {
330 		printf("%s (%d/%d)\n", msg, i, num);
331 		verb_cert(NULL, sk_X509_value(sk, i));
332 	}
333 }
334 
335 /** read certificates from a PEM bio */
336 static STACK_OF(X509)*
337 read_cert_bio(BIO* bio)
338 {
339 	STACK_OF(X509) *sk = sk_X509_new_null();
340 	if(!sk) {
341 		if(verb) printf("out of memory\n");
342 		exit(0);
343 	}
344 	while(!BIO_eof(bio)) {
345 		X509* x = PEM_read_bio_X509(bio, NULL, 0, NULL);
346 		if(x == NULL) {
347 			if(verb) {
348 				printf("failed to read X509\n");
349 			 	ERR_print_errors_fp(stdout);
350 			}
351 			continue;
352 		}
353 		if(!sk_X509_push(sk, x)) {
354 			if(verb) printf("out of memory\n");
355 			exit(0);
356 		}
357 	}
358 	return sk;
359 }
360 
361 /* read the certificate file */
362 static STACK_OF(X509)*
363 read_cert_file(const char* file)
364 {
365 	STACK_OF(X509)* sk;
366 	FILE* in;
367 	int content = 0;
368 	char buf[128];
369 	if(file == NULL || strcmp(file, "") == 0) {
370 		return NULL;
371 	}
372 	sk = sk_X509_new_null();
373 	if(!sk) {
374 		if(verb) printf("out of memory\n");
375 		exit(0);
376 	}
377 	in = fopen(file, "r");
378 	if(!in) {
379 		if(verb) printf("%s: %s\n", file, strerror(errno));
380 #ifndef S_SPLINT_S
381 		sk_X509_pop_free(sk, X509_free);
382 #endif
383 		return NULL;
384 	}
385 	while(!feof(in)) {
386 		X509* x = PEM_read_X509(in, NULL, 0, NULL);
387 		if(x == NULL) {
388 			if(verb) {
389 				printf("failed to read X509 file\n");
390 			 	ERR_print_errors_fp(stdout);
391 			}
392 			continue;
393 		}
394 		if(!sk_X509_push(sk, x)) {
395 			if(verb) printf("out of memory\n");
396 			fclose(in);
397 			exit(0);
398 		}
399 		content = 1;
400 		/* read away newline after --END CERT-- */
401 		if(!fgets(buf, (int)sizeof(buf), in))
402 			break;
403 	}
404 	fclose(in);
405 	if(!content) {
406 		if(verb) printf("%s is empty\n", file);
407 #ifndef S_SPLINT_S
408 		sk_X509_pop_free(sk, X509_free);
409 #endif
410 		return NULL;
411 	}
412 	return sk;
413 }
414 
415 /** read certificates from the builtin certificate */
416 static STACK_OF(X509)*
417 read_builtin_cert(void)
418 {
419 	const char* builtin_cert = get_builtin_cert();
420 	STACK_OF(X509)* sk;
421 	BIO *bio = BIO_new_mem_buf((void*)builtin_cert,
422 		(int)strlen(builtin_cert));
423 	if(!bio) {
424 		if(verb) printf("out of memory\n");
425 		exit(0);
426 	}
427 	sk = read_cert_bio(bio);
428 	if(!sk) {
429 		if(verb) printf("internal error, out of memory\n");
430 		exit(0);
431 	}
432 	BIO_free(bio);
433 	return sk;
434 }
435 
436 /** read update cert file or use builtin */
437 static STACK_OF(X509)*
438 read_cert_or_builtin(const char* file)
439 {
440 	STACK_OF(X509) *sk = read_cert_file(file);
441 	if(!sk) {
442 		if(verb) printf("using builtin certificate\n");
443 		sk = read_builtin_cert();
444 	}
445 	if(verb) printf("have %d trusted certificates\n", sk_X509_num(sk));
446 	verb_certs("trusted certificates", sk);
447 	return sk;
448 }
449 
450 static void
451 do_list_builtin(void)
452 {
453 	const char* builtin_cert = get_builtin_cert();
454 	const char* builtin_ds = get_builtin_ds();
455 	printf("%s\n", builtin_ds);
456 	printf("%s\n", builtin_cert);
457 	exit(0);
458 }
459 
460 /** printout IP address with message */
461 static void
462 verb_addr(const char* msg, struct ip_list* ip)
463 {
464 	if(verb) {
465 		char out[100];
466 		void* a = &((struct sockaddr_in*)&ip->addr)->sin_addr;
467 		if(ip->len != (socklen_t)sizeof(struct sockaddr_in))
468 			a = &((struct sockaddr_in6*)&ip->addr)->sin6_addr;
469 
470 		if(inet_ntop((int)((struct sockaddr_in*)&ip->addr)->sin_family,
471 			a, out, (socklen_t)sizeof(out))==0)
472 			printf("%s (inet_ntop error)\n", msg);
473 		else printf("%s %s\n", msg, out);
474 	}
475 }
476 
477 /** free ip_list */
478 static void
479 ip_list_free(struct ip_list* p)
480 {
481 	struct ip_list* np;
482 	while(p) {
483 		np = p->next;
484 		free(p);
485 		p = np;
486 	}
487 }
488 
489 /** create ip_list entry for a RR record */
490 static struct ip_list*
491 RR_to_ip(int tp, char* data, int len, int port)
492 {
493 	struct ip_list* ip = (struct ip_list*)calloc(1, sizeof(*ip));
494 	uint16_t p = (uint16_t)port;
495 	if(tp == LDNS_RR_TYPE_A) {
496 		struct sockaddr_in* sa = (struct sockaddr_in*)&ip->addr;
497 		ip->len = (socklen_t)sizeof(*sa);
498 		sa->sin_family = AF_INET;
499 		sa->sin_port = (in_port_t)htons(p);
500 		if(len != (int)sizeof(sa->sin_addr)) {
501 			if(verb) printf("skipped badly formatted A\n");
502 			free(ip);
503 			return NULL;
504 		}
505 		memmove(&sa->sin_addr, data, sizeof(sa->sin_addr));
506 
507 	} else if(tp == LDNS_RR_TYPE_AAAA) {
508 		struct sockaddr_in6* sa = (struct sockaddr_in6*)&ip->addr;
509 		ip->len = (socklen_t)sizeof(*sa);
510 		sa->sin6_family = AF_INET6;
511 		sa->sin6_port = (in_port_t)htons(p);
512 		if(len != (int)sizeof(sa->sin6_addr)) {
513 			if(verb) printf("skipped badly formatted AAAA\n");
514 			free(ip);
515 			return NULL;
516 		}
517 		memmove(&sa->sin6_addr, data, sizeof(sa->sin6_addr));
518 	} else {
519 		if(verb) printf("internal error: bad type in RRtoip\n");
520 		free(ip);
521 		return NULL;
522 	}
523 	verb_addr("resolved server address", ip);
524 	return ip;
525 }
526 
527 /** Resolve name, type, class and add addresses to iplist */
528 static void
529 resolve_host_ip(struct ub_ctx* ctx, const char* host, int port, int tp, int cl,
530 	struct ip_list** head)
531 {
532 	struct ub_result* res = NULL;
533 	int r;
534 	int i;
535 
536 	r = ub_resolve(ctx, host, tp, cl, &res);
537 	if(r) {
538 		if(verb) printf("error: resolve %s %s: %s\n", host,
539 			(tp==LDNS_RR_TYPE_A)?"A":"AAAA", ub_strerror(r));
540 		return;
541 	}
542 	if(!res) {
543 		if(verb) printf("out of memory\n");
544 		ub_ctx_delete(ctx);
545 		exit(0);
546 	}
547 	if(!res->havedata || res->rcode || !res->data) {
548 		if(verb) printf("resolve %s %s: no result\n", host,
549 			(tp==LDNS_RR_TYPE_A)?"A":"AAAA");
550 		return;
551 	}
552 	for(i = 0; res->data[i]; i++) {
553 		struct ip_list* ip = RR_to_ip(tp, res->data[i], res->len[i],
554 			port);
555 		if(!ip) continue;
556 		ip->next = *head;
557 		*head = ip;
558 	}
559 	ub_resolve_free(res);
560 }
561 
562 /** parse a text IP address into a sockaddr */
563 static struct ip_list*
564 parse_ip_addr(const char* str, int port)
565 {
566 	socklen_t len = 0;
567 	union {
568 		struct sockaddr_in6 a6;
569 		struct sockaddr_in a;
570 	} addr;
571 	struct ip_list* ip;
572 	uint16_t p = (uint16_t)port;
573 	memset(&addr, 0, sizeof(addr));
574 
575 	if(inet_pton(AF_INET6, str, &addr.a6.sin6_addr) > 0) {
576 		/* it is an IPv6 */
577 		addr.a6.sin6_family = AF_INET6;
578 		addr.a6.sin6_port = (in_port_t)htons(p);
579 		len = (socklen_t)sizeof(addr.a6);
580 	}
581 	if(inet_pton(AF_INET, str, &addr.a.sin_addr) > 0) {
582 		/* it is an IPv4 */
583 		addr.a.sin_family = AF_INET;
584 		addr.a.sin_port = (in_port_t)htons(p);
585 		len = (socklen_t)sizeof(struct sockaddr_in);
586 	}
587 	if(!len) return NULL;
588 	ip = (struct ip_list*)calloc(1, sizeof(*ip));
589 	if(!ip) {
590 		if(verb) printf("out of memory\n");
591 		exit(0);
592 	}
593 	ip->len = len;
594 	memmove(&ip->addr, &addr, len);
595 	if(verb) printf("server address is %s\n", str);
596 	return ip;
597 }
598 
599 /**
600  * Resolve a domain name (even though the resolver is down and there is
601  * no trust anchor).  Without DNSSEC validation.
602  * @param host: the name to resolve.
603  * 	If this name is an IP4 or IP6 address this address is returned.
604  * @param port: the port number used for the returned IP structs.
605  * @param res_conf: resolv.conf (if any).
606  * @param root_hints: root hints (if any).
607  * @param debugconf: unbound.conf for debugging options.
608  * @param ip4only: use only ip4 for resolve and only lookup A
609  * @param ip6only: use only ip6 for resolve and only lookup AAAA
610  * 	default is to lookup A and AAAA using ip4 and ip6.
611  * @return list of IP addresses.
612  */
613 static struct ip_list*
614 resolve_name(const char* host, int port, const char* res_conf,
615 	const char* root_hints, const char* debugconf, int ip4only, int ip6only)
616 {
617 	struct ub_ctx* ctx;
618 	struct ip_list* list = NULL;
619 	/* first see if name is an IP address itself */
620 	if( (list=parse_ip_addr(host, port)) ) {
621 		return list;
622 	}
623 
624 	/* create resolver context */
625 	ctx = create_unbound_context(res_conf, root_hints, debugconf,
626         	ip4only, ip6only);
627 
628 	/* try resolution of A */
629 	if(!ip6only) {
630 		resolve_host_ip(ctx, host, port, LDNS_RR_TYPE_A,
631 			LDNS_RR_CLASS_IN, &list);
632 	}
633 
634 	/* try resolution of AAAA */
635 	if(!ip4only) {
636 		resolve_host_ip(ctx, host, port, LDNS_RR_TYPE_AAAA,
637 			LDNS_RR_CLASS_IN, &list);
638 	}
639 
640 	ub_ctx_delete(ctx);
641 	if(!list) {
642 		if(verb) printf("%s has no IP addresses I can use\n", host);
643 		exit(0);
644 	}
645 	return list;
646 }
647 
648 /** clear used flags */
649 static void
650 wipe_ip_usage(struct ip_list* p)
651 {
652 	while(p) {
653 		p->used = 0;
654 		p = p->next;
655 	}
656 }
657 
658 /** cound unused IPs */
659 static int
660 count_unused(struct ip_list* p)
661 {
662 	int num = 0;
663 	while(p) {
664 		if(!p->used) num++;
665 		p = p->next;
666 	}
667 	return num;
668 }
669 
670 /** pick random unused element from IP list */
671 static struct ip_list*
672 pick_random_ip(struct ip_list* list)
673 {
674 	struct ip_list* p = list;
675 	int num = count_unused(list);
676 	int sel;
677 	if(num == 0) return NULL;
678 	/* not perfect, but random enough */
679 	sel = (int)arc4random_uniform((uint32_t)num);
680 	/* skip over unused elements that we did not select */
681 	while(sel > 0 && p) {
682 		if(!p->used) sel--;
683 		p = p->next;
684 	}
685 	/* find the next unused element */
686 	while(p && p->used)
687 		p = p->next;
688 	if(!p) return NULL; /* robustness */
689 	return p;
690 }
691 
692 /** close the fd */
693 static void
694 fd_close(int fd)
695 {
696 #ifndef USE_WINSOCK
697 	close(fd);
698 #else
699 	closesocket(fd);
700 #endif
701 }
702 
703 /** printout socket errno */
704 static void
705 print_sock_err(const char* msg)
706 {
707 #ifndef USE_WINSOCK
708 	if(verb) printf("%s: %s\n", msg, strerror(errno));
709 #else
710 	if(verb) printf("%s: %s\n", msg, wsa_strerror(WSAGetLastError()));
711 #endif
712 }
713 
714 /** connect to IP address */
715 static int
716 connect_to_ip(struct ip_list* ip)
717 {
718 	int fd;
719 	verb_addr("connect to", ip);
720 	fd = socket(ip->len==(socklen_t)sizeof(struct sockaddr_in)?
721 		AF_INET:AF_INET6, SOCK_STREAM, 0);
722 	if(fd == -1) {
723 		print_sock_err("socket");
724 		return -1;
725 	}
726 	if(connect(fd, (struct sockaddr*)&ip->addr, ip->len) < 0) {
727 		print_sock_err("connect");
728 		fd_close(fd);
729 		return -1;
730 	}
731 	return fd;
732 }
733 
734 /** create SSL context */
735 static SSL_CTX*
736 setup_sslctx(void)
737 {
738 	SSL_CTX* sslctx = SSL_CTX_new(SSLv23_client_method());
739 	if(!sslctx) {
740 		if(verb) printf("SSL_CTX_new error\n");
741 		return NULL;
742 	}
743 	return sslctx;
744 }
745 
746 /** initiate TLS on a connection */
747 static SSL*
748 TLS_initiate(SSL_CTX* sslctx, int fd)
749 {
750 	X509* x;
751 	int r;
752 	SSL* ssl = SSL_new(sslctx);
753 	if(!ssl) {
754 		if(verb) printf("SSL_new error\n");
755 		return NULL;
756 	}
757 	SSL_set_connect_state(ssl);
758 	(void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
759 	if(!SSL_set_fd(ssl, fd)) {
760 		if(verb) printf("SSL_set_fd error\n");
761 		SSL_free(ssl);
762 		return NULL;
763 	}
764 	while(1) {
765 		ERR_clear_error();
766 		if( (r=SSL_do_handshake(ssl)) == 1)
767 			break;
768 		r = SSL_get_error(ssl, r);
769 		if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) {
770 			if(verb) printf("SSL handshake failed\n");
771 			SSL_free(ssl);
772 			return NULL;
773 		}
774 		/* wants to be called again */
775 	}
776 	x = SSL_get_peer_certificate(ssl);
777 	if(!x) {
778 		if(verb) printf("Server presented no peer certificate\n");
779 		SSL_free(ssl);
780 		return NULL;
781 	}
782 	verb_cert("server SSL certificate", x);
783 	X509_free(x);
784 	return ssl;
785 }
786 
787 /** perform neat TLS shutdown */
788 static void
789 TLS_shutdown(int fd, SSL* ssl, SSL_CTX* sslctx)
790 {
791 	/* shutdown the SSL connection nicely */
792 	if(SSL_shutdown(ssl) == 0) {
793 		SSL_shutdown(ssl);
794 	}
795 	SSL_free(ssl);
796 	SSL_CTX_free(sslctx);
797 	fd_close(fd);
798 }
799 
800 /** write a line over SSL */
801 static int
802 write_ssl_line(SSL* ssl, const char* str, const char* sec)
803 {
804 	char buf[1024];
805 	size_t l;
806 	if(sec) {
807 		snprintf(buf, sizeof(buf), str, sec);
808 	} else {
809 		snprintf(buf, sizeof(buf), "%s", str);
810 	}
811 	l = strlen(buf);
812 	if(l+2 >= sizeof(buf)) {
813 		if(verb) printf("line too long\n");
814 		return 0;
815 	}
816 	if(verb >= 2) printf("SSL_write: %s\n", buf);
817 	buf[l] = '\r';
818 	buf[l+1] = '\n';
819 	buf[l+2] = 0;
820 	/* add \r\n */
821 	if(SSL_write(ssl, buf, (int)strlen(buf)) <= 0) {
822 		if(verb) printf("could not SSL_write %s", str);
823 		return 0;
824 	}
825 	return 1;
826 }
827 
828 /** process header line, check rcode and keeping track of size */
829 static int
830 process_one_header(char* buf, size_t* clen, int* chunked)
831 {
832 	if(verb>=2) printf("header: '%s'\n", buf);
833 	if(strncasecmp(buf, "HTTP/1.1 ", 9) == 0) {
834 		/* check returncode */
835 		if(buf[9] != '2') {
836 			if(verb) printf("bad status %s\n", buf+9);
837 			return 0;
838 		}
839 	} else if(strncasecmp(buf, "Content-Length: ", 16) == 0) {
840 		if(!*chunked)
841 			*clen = (size_t)atoi(buf+16);
842 	} else if(strncasecmp(buf, "Transfer-Encoding: chunked", 19+7) == 0) {
843 		*clen = 0;
844 		*chunked = 1;
845 	}
846 	return 1;
847 }
848 
849 /**
850  * Read one line from SSL
851  * zero terminates.
852  * skips "\r\n" (but not copied to buf).
853  * @param ssl: the SSL connection to read from (blocking).
854  * @param buf: buffer to return line in.
855  * @param len: size of the buffer.
856  * @return 0 on error, 1 on success.
857  */
858 static int
859 read_ssl_line(SSL* ssl, char* buf, size_t len)
860 {
861 	size_t n = 0;
862 	int r;
863 	int endnl = 0;
864 	while(1) {
865 		if(n >= len) {
866 			if(verb) printf("line too long\n");
867 			return 0;
868 		}
869 		if((r = SSL_read(ssl, buf+n, 1)) <= 0) {
870 			if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
871 				/* EOF */
872 				break;
873 			}
874 			if(verb) printf("could not SSL_read\n");
875 			return 0;
876 		}
877 		if(endnl && buf[n] == '\n') {
878 			break;
879 		} else if(endnl) {
880 			/* bad data */
881 			if(verb) printf("error: stray linefeeds\n");
882 			return 0;
883 		} else if(buf[n] == '\r') {
884 			/* skip \r, and also \n on the wire */
885 			endnl = 1;
886 			continue;
887 		} else if(buf[n] == '\n') {
888 			/* skip the \n, we are done */
889 			break;
890 		} else n++;
891 	}
892 	buf[n] = 0;
893 	return 1;
894 }
895 
896 /** read http headers and process them */
897 static size_t
898 read_http_headers(SSL* ssl, size_t* clen)
899 {
900 	char buf[1024];
901 	int chunked = 0;
902 	*clen = 0;
903 	while(read_ssl_line(ssl, buf, sizeof(buf))) {
904 		if(buf[0] == 0)
905 			return 1;
906 		if(!process_one_header(buf, clen, &chunked))
907 			return 0;
908 	}
909 	return 0;
910 }
911 
912 /** read a data chunk */
913 static char*
914 read_data_chunk(SSL* ssl, size_t len)
915 {
916 	size_t got = 0;
917 	int r;
918 	char* data = malloc(len+1);
919 	if(!data) {
920 		if(verb) printf("out of memory\n");
921 		return NULL;
922 	}
923 	while(got < len) {
924 		if((r = SSL_read(ssl, data+got, (int)(len-got))) <= 0) {
925 			if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
926 				/* EOF */
927 				if(verb) printf("could not SSL_read: unexpected EOF\n");
928 				free(data);
929 				return NULL;
930 			}
931 			if(verb) printf("could not SSL_read\n");
932 			free(data);
933 			return NULL;
934 		}
935 		if(verb >= 2) printf("at %d/%d\n", (int)got, (int)len);
936 		got += r;
937 	}
938 	if(verb>=2) printf("read %d data\n", (int)len);
939 	data[len] = 0;
940 	return data;
941 }
942 
943 /** parse chunk header */
944 static int
945 parse_chunk_header(char* buf, size_t* result)
946 {
947 	char* e = NULL;
948 	size_t v = (size_t)strtol(buf, &e, 16);
949 	if(e == buf)
950 		return 0;
951 	*result = v;
952 	return 1;
953 }
954 
955 /** read chunked data from connection */
956 static BIO*
957 do_chunked_read(SSL* ssl)
958 {
959 	char buf[1024];
960 	size_t len;
961 	char* body;
962 	BIO* mem = BIO_new(BIO_s_mem());
963 	if(verb>=3) printf("do_chunked_read\n");
964 	if(!mem) {
965 		if(verb) printf("out of memory\n");
966 		return NULL;
967 	}
968 	while(read_ssl_line(ssl, buf, sizeof(buf))) {
969 		/* read the chunked start line */
970 		if(verb>=2) printf("chunk header: %s\n", buf);
971 		if(!parse_chunk_header(buf, &len)) {
972 			BIO_free(mem);
973 			if(verb>=3) printf("could not parse chunk header\n");
974 			return NULL;
975 		}
976 		if(verb>=2) printf("chunk len: %d\n", (int)len);
977 		/* are we done? */
978 		if(len == 0) {
979 			char z = 0;
980 			/* skip end-of-chunk-trailer lines,
981 			 * until the empty line after that */
982 			do {
983 				if(!read_ssl_line(ssl, buf, sizeof(buf))) {
984 					BIO_free(mem);
985 					return NULL;
986 				}
987 			} while (strlen(buf) > 0);
988 			/* end of chunks, zero terminate it */
989 			if(BIO_write(mem, &z, 1) <= 0) {
990 				if(verb) printf("out of memory\n");
991 				BIO_free(mem);
992 				return NULL;
993 			}
994 			return mem;
995 		}
996 		/* read the chunked body */
997 		body = read_data_chunk(ssl, len);
998 		if(!body) {
999 			BIO_free(mem);
1000 			return NULL;
1001 		}
1002 		if(BIO_write(mem, body, (int)len) <= 0) {
1003 			if(verb) printf("out of memory\n");
1004 			free(body);
1005 			BIO_free(mem);
1006 			return NULL;
1007 		}
1008 		free(body);
1009 		/* skip empty line after data chunk */
1010 		if(!read_ssl_line(ssl, buf, sizeof(buf))) {
1011 			BIO_free(mem);
1012 			return NULL;
1013 		}
1014 	}
1015 	BIO_free(mem);
1016 	return NULL;
1017 }
1018 
1019 /** start HTTP1.1 transaction on SSL */
1020 static int
1021 write_http_get(SSL* ssl, const char* pathname, const char* urlname)
1022 {
1023 	if(write_ssl_line(ssl, "GET /%s HTTP/1.1", pathname) &&
1024 	   write_ssl_line(ssl, "Host: %s", urlname) &&
1025 	   write_ssl_line(ssl, "User-Agent: unbound-anchor/%s",
1026 	   	PACKAGE_VERSION) &&
1027 	   /* We do not really do multiple queries per connection,
1028 	    * but this header setting is also not needed.
1029 	    * write_ssl_line(ssl, "Connection: close", NULL) &&*/
1030 	   write_ssl_line(ssl, "", NULL)) {
1031 		return 1;
1032 	}
1033 	return 0;
1034 }
1035 
1036 /** read chunked data and zero terminate; len is without zero */
1037 static char*
1038 read_chunked_zero_terminate(SSL* ssl, size_t* len)
1039 {
1040 	/* do the chunked version */
1041 	BIO* tmp = do_chunked_read(ssl);
1042 	char* data, *d = NULL;
1043 	size_t l;
1044 	if(!tmp) {
1045 		if(verb) printf("could not read from https\n");
1046 		return NULL;
1047 	}
1048 	l = (size_t)BIO_get_mem_data(tmp, &d);
1049 	if(verb>=2) printf("chunked data is %d\n", (int)l);
1050 	if(l == 0 || d == NULL) {
1051 		if(verb) printf("out of memory\n");
1052 		return NULL;
1053 	}
1054 	*len = l-1;
1055 	data = (char*)malloc(l);
1056 	if(data == NULL) {
1057 		if(verb) printf("out of memory\n");
1058 		return NULL;
1059 	}
1060 	memcpy(data, d, l);
1061 	BIO_free(tmp);
1062 	return data;
1063 }
1064 
1065 /** read HTTP result from SSL */
1066 static BIO*
1067 read_http_result(SSL* ssl)
1068 {
1069 	size_t len = 0;
1070 	char* data;
1071 	BIO* m;
1072 	if(!read_http_headers(ssl, &len)) {
1073 		return NULL;
1074 	}
1075 	if(len == 0) {
1076 		data = read_chunked_zero_terminate(ssl, &len);
1077 	} else {
1078 		data = read_data_chunk(ssl, len);
1079 	}
1080 	if(!data) return NULL;
1081 	if(verb >= 4) print_data("read data", data, (int)len);
1082 	m = BIO_new_mem_buf(data, (int)len);
1083 	if(!m) {
1084 		if(verb) printf("out of memory\n");
1085 		exit(0);
1086 	}
1087 	return m;
1088 }
1089 
1090 /** https to an IP addr, return BIO with pathname or NULL */
1091 static BIO*
1092 https_to_ip(struct ip_list* ip, const char* pathname, const char* urlname)
1093 {
1094 	int fd;
1095 	SSL* ssl;
1096 	BIO* bio;
1097 	SSL_CTX* sslctx = setup_sslctx();
1098 	if(!sslctx) {
1099 		return NULL;
1100 	}
1101 	fd = connect_to_ip(ip);
1102 	if(fd == -1) {
1103 		SSL_CTX_free(sslctx);
1104 		return NULL;
1105 	}
1106 	ssl = TLS_initiate(sslctx, fd);
1107 	if(!ssl) {
1108 		SSL_CTX_free(sslctx);
1109 		fd_close(fd);
1110 		return NULL;
1111 	}
1112 	if(!write_http_get(ssl, pathname, urlname)) {
1113 		if(verb) printf("could not write to server\n");
1114 		SSL_free(ssl);
1115 		SSL_CTX_free(sslctx);
1116 		fd_close(fd);
1117 		return NULL;
1118 	}
1119 	bio = read_http_result(ssl);
1120 	TLS_shutdown(fd, ssl, sslctx);
1121 	return bio;
1122 }
1123 
1124 /**
1125  * Do a HTTPS, HTTP1.1 over TLS, to fetch a file
1126  * @param ip_list: list of IP addresses to use to fetch from.
1127  * @param pathname: pathname of file on server to GET.
1128  * @param urlname: name to pass as the virtual host for this request.
1129  * @return a memory BIO with the file in it.
1130  */
1131 static BIO*
1132 https(struct ip_list* ip_list, const char* pathname, const char* urlname)
1133 {
1134 	struct ip_list* ip;
1135 	BIO* bio = NULL;
1136 	/* try random address first, and work through the list */
1137 	wipe_ip_usage(ip_list);
1138 	while( (ip = pick_random_ip(ip_list)) ) {
1139 		ip->used = 1;
1140 		bio = https_to_ip(ip, pathname, urlname);
1141 		if(bio) break;
1142 	}
1143 	if(!bio) {
1144 		if(verb) printf("could not fetch %s\n", pathname);
1145 		exit(0);
1146 	} else {
1147 		if(verb) printf("fetched %s (%d bytes)\n",
1148 			pathname, (int)BIO_ctrl_pending(bio));
1149 	}
1150 	return bio;
1151 }
1152 
1153 /** free up a downloaded file BIO */
1154 static void
1155 free_file_bio(BIO* bio)
1156 {
1157 	char* pp = NULL;
1158 	(void)BIO_reset(bio);
1159 	(void)BIO_get_mem_data(bio, &pp);
1160 	free(pp);
1161 	BIO_free(bio);
1162 }
1163 
1164 /** XML parse private data during the parse */
1165 struct xml_data {
1166 	/** the parser, reference */
1167 	XML_Parser parser;
1168 	/** the current tag; malloced; or NULL outside of tags */
1169 	char* tag;
1170 	/** current date to use during the parse */
1171 	time_t date;
1172 	/** number of keys usefully read in */
1173 	int num_keys;
1174 	/** the compiled anchors as DS records */
1175 	BIO* ds;
1176 
1177 	/** do we want to use this anchor? */
1178 	int use_key;
1179 	/** the current anchor: Zone */
1180 	BIO* czone;
1181 	/** the current anchor: KeyTag */
1182 	BIO* ctag;
1183 	/** the current anchor: Algorithm */
1184 	BIO* calgo;
1185 	/** the current anchor: DigestType */
1186 	BIO* cdigtype;
1187 	/** the current anchor: Digest*/
1188 	BIO* cdigest;
1189 };
1190 
1191 /** The BIO for the tag */
1192 static BIO*
1193 xml_selectbio(struct xml_data* data, const char* tag)
1194 {
1195 	BIO* b = NULL;
1196 	if(strcasecmp(tag, "KeyTag") == 0)
1197 		b = data->ctag;
1198 	else if(strcasecmp(tag, "Algorithm") == 0)
1199 		b = data->calgo;
1200 	else if(strcasecmp(tag, "DigestType") == 0)
1201 		b = data->cdigtype;
1202 	else if(strcasecmp(tag, "Digest") == 0)
1203 		b = data->cdigest;
1204 	return b;
1205 }
1206 
1207 /**
1208  * XML handle character data, the data inside an element.
1209  * @param userData: xml_data structure
1210  * @param s: the character data.  May not all be in one callback.
1211  * 	NOT zero terminated.
1212  * @param len: length of this part of the data.
1213  */
1214 static void
1215 xml_charhandle(void *userData, const XML_Char *s, int len)
1216 {
1217 	struct xml_data* data = (struct xml_data*)userData;
1218 	BIO* b = NULL;
1219 	/* skip characters outside of elements */
1220 	if(!data->tag)
1221 		return;
1222 	if(verb>=4) {
1223 		int i;
1224 		printf("%s%s charhandle: '",
1225 			data->use_key?"use ":"",
1226 			data->tag?data->tag:"none");
1227 		for(i=0; i<len; i++)
1228 			printf("%c", s[i]);
1229 		printf("'\n");
1230 	}
1231 	if(strcasecmp(data->tag, "Zone") == 0) {
1232 		if(BIO_write(data->czone, s, len) < 0) {
1233 			if(verb) printf("out of memory in BIO_write\n");
1234 			exit(0);
1235 		}
1236 		return;
1237 	}
1238 	/* only store if key is used */
1239 	if(!data->use_key)
1240 		return;
1241 	b = xml_selectbio(data, data->tag);
1242 	if(b) {
1243 		if(BIO_write(b, s, len) < 0) {
1244 			if(verb) printf("out of memory in BIO_write\n");
1245 			exit(0);
1246 		}
1247 	}
1248 }
1249 
1250 /**
1251  * XML fetch value of particular attribute(by name) or NULL if not present.
1252  * @param atts: attribute array (from xml_startelem).
1253  * @param name: name of attribute to look for.
1254  * @return the value or NULL. (ptr into atts).
1255  */
1256 static const XML_Char*
1257 find_att(const XML_Char **atts, const XML_Char* name)
1258 {
1259 	int i;
1260 	for(i=0; atts[i]; i+=2) {
1261 		if(strcasecmp(atts[i], name) == 0)
1262 			return atts[i+1];
1263 	}
1264 	return NULL;
1265 }
1266 
1267 /**
1268  * XML convert DateTime element to time_t.
1269  * [-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
1270  * (with optional .ssssss fractional seconds)
1271  * @param str: the string
1272  * @return a time_t representation or 0 on failure.
1273  */
1274 static time_t
1275 xml_convertdate(const char* str)
1276 {
1277 	time_t t = 0;
1278 	struct tm tm;
1279 	const char* s;
1280 	/* for this application, ignore minus in front;
1281 	 * only positive dates are expected */
1282 	s = str;
1283 	if(s[0] == '-') s++;
1284 	memset(&tm, 0, sizeof(tm));
1285 	/* parse initial content of the string (lots of whitespace allowed) */
1286 	s = strptime(s, "%t%Y%t-%t%m%t-%t%d%tT%t%H%t:%t%M%t:%t%S%t", &tm);
1287 	if(!s) {
1288 		if(verb) printf("xml_convertdate parse failure %s\n", str);
1289 		return 0;
1290 	}
1291 	/* parse remainder of date string */
1292 	if(*s == '.') {
1293 		/* optional '.' and fractional seconds */
1294 		int frac = 0, n = 0;
1295 		if(sscanf(s+1, "%d%n", &frac, &n) < 1) {
1296 			if(verb) printf("xml_convertdate f failure %s\n", str);
1297 			return 0;
1298 		}
1299 		/* fraction is not used, time_t has second accuracy */
1300 		s++;
1301 		s+=n;
1302 	}
1303 	if(*s == 'Z' || *s == 'z') {
1304 		/* nothing to do for this */
1305 		s++;
1306 	} else if(*s == '+' || *s == '-') {
1307 		/* optional timezone spec: Z or +hh:mm or -hh:mm */
1308 		int hr = 0, mn = 0, n = 0;
1309 		if(sscanf(s+1, "%d:%d%n", &hr, &mn, &n) < 2) {
1310 			if(verb) printf("xml_convertdate tz failure %s\n", str);
1311 			return 0;
1312 		}
1313 		if(*s == '+') {
1314 			tm.tm_hour += hr;
1315 			tm.tm_min += mn;
1316 		} else {
1317 			tm.tm_hour -= hr;
1318 			tm.tm_min -= mn;
1319 		}
1320 		s++;
1321 		s += n;
1322 	}
1323 	if(*s != 0) {
1324 		/* not ended properly */
1325 		/* but ignore, (lenient) */
1326 	}
1327 
1328 	t = mktime(&tm);
1329 	if(t == (time_t)-1) {
1330 		if(verb) printf("xml_convertdate mktime failure\n");
1331 		return 0;
1332 	}
1333 	return t;
1334 }
1335 
1336 /**
1337  * XML handle the KeyDigest start tag, check validity periods.
1338  */
1339 static void
1340 handle_keydigest(struct xml_data* data, const XML_Char **atts)
1341 {
1342 	data->use_key = 0;
1343 	if(find_att(atts, "validFrom")) {
1344 		time_t from = xml_convertdate(find_att(atts, "validFrom"));
1345 		if(from == 0) {
1346 			if(verb) printf("error: xml cannot be parsed\n");
1347 			exit(0);
1348 		}
1349 		if(data->date < from)
1350 			return;
1351 	}
1352 	if(find_att(atts, "validUntil")) {
1353 		time_t until = xml_convertdate(find_att(atts, "validUntil"));
1354 		if(until == 0) {
1355 			if(verb) printf("error: xml cannot be parsed\n");
1356 			exit(0);
1357 		}
1358 		if(data->date > until)
1359 			return;
1360 	}
1361 	/* yes we want to use this key */
1362 	data->use_key = 1;
1363 	(void)BIO_reset(data->ctag);
1364 	(void)BIO_reset(data->calgo);
1365 	(void)BIO_reset(data->cdigtype);
1366 	(void)BIO_reset(data->cdigest);
1367 }
1368 
1369 /** See if XML element equals the zone name */
1370 static int
1371 xml_is_zone_name(BIO* zone, const char* name)
1372 {
1373 	char buf[1024];
1374 	char* z = NULL;
1375 	long zlen;
1376 	(void)BIO_seek(zone, 0);
1377 	zlen = BIO_get_mem_data(zone, &z);
1378 	if(!zlen || !z) return 0;
1379 	/* zero terminate */
1380 	if(zlen >= (long)sizeof(buf)) return 0;
1381 	memmove(buf, z, (size_t)zlen);
1382 	buf[zlen] = 0;
1383 	/* compare */
1384 	return (strncasecmp(buf, name, strlen(name)) == 0);
1385 }
1386 
1387 /**
1388  * XML start of element. This callback is called whenever an XML tag starts.
1389  * XML_Char is UTF8.
1390  * @param userData: the xml_data structure.
1391  * @param name: the tag that starts.
1392  * @param atts: array of strings, pairs of attr = value, ends with NULL.
1393  * 	i.e. att[0]="att[1]" att[2]="att[3]" att[4]isNull
1394  */
1395 static void
1396 xml_startelem(void *userData, const XML_Char *name, const XML_Char **atts)
1397 {
1398 	struct xml_data* data = (struct xml_data*)userData;
1399 	BIO* b;
1400 	if(verb>=4) printf("xml tag start '%s'\n", name);
1401 	free(data->tag);
1402 	data->tag = strdup(name);
1403 	if(!data->tag) {
1404 		if(verb) printf("out of memory\n");
1405 		exit(0);
1406 	}
1407 	if(verb>=4) {
1408 		int i;
1409 		for(i=0; atts[i]; i+=2) {
1410 			printf("  %s='%s'\n", atts[i], atts[i+1]);
1411 		}
1412 	}
1413 	/* handle attributes to particular types */
1414 	if(strcasecmp(name, "KeyDigest") == 0) {
1415 		handle_keydigest(data, atts);
1416 		return;
1417 	} else if(strcasecmp(name, "Zone") == 0) {
1418 		(void)BIO_reset(data->czone);
1419 		return;
1420 	}
1421 
1422 	/* for other types we prepare to pick up the data */
1423 	if(!data->use_key)
1424 		return;
1425 	b = xml_selectbio(data, data->tag);
1426 	if(b) {
1427 		/* empty it */
1428 		(void)BIO_reset(b);
1429 	}
1430 }
1431 
1432 /** Append str to bio */
1433 static void
1434 xml_append_str(BIO* b, const char* s)
1435 {
1436 	if(BIO_write(b, s, (int)strlen(s)) < 0) {
1437 		if(verb) printf("out of memory in BIO_write\n");
1438 		exit(0);
1439 	}
1440 }
1441 
1442 /** Append bio to bio */
1443 static void
1444 xml_append_bio(BIO* b, BIO* a)
1445 {
1446 	char* z = NULL;
1447 	long i, len;
1448 	(void)BIO_seek(a, 0);
1449 	len = BIO_get_mem_data(a, &z);
1450 	if(!len || !z) {
1451 		if(verb) printf("out of memory in BIO_write\n");
1452 		exit(0);
1453 	}
1454 	/* remove newlines in the data here */
1455 	for(i=0; i<len; i++) {
1456 		if(z[i] == '\r' || z[i] == '\n')
1457 			z[i] = ' ';
1458 	}
1459 	/* write to BIO */
1460 	if(BIO_write(b, z, len) < 0) {
1461 		if(verb) printf("out of memory in BIO_write\n");
1462 		exit(0);
1463 	}
1464 }
1465 
1466 /** write the parsed xml-DS to the DS list */
1467 static void
1468 xml_append_ds(struct xml_data* data)
1469 {
1470 	/* write DS to accumulated DS */
1471 	xml_append_str(data->ds, ". IN DS ");
1472 	xml_append_bio(data->ds, data->ctag);
1473 	xml_append_str(data->ds, " ");
1474 	xml_append_bio(data->ds, data->calgo);
1475 	xml_append_str(data->ds, " ");
1476 	xml_append_bio(data->ds, data->cdigtype);
1477 	xml_append_str(data->ds, " ");
1478 	xml_append_bio(data->ds, data->cdigest);
1479 	xml_append_str(data->ds, "\n");
1480 	data->num_keys++;
1481 }
1482 
1483 /**
1484  * XML end of element. This callback is called whenever an XML tag ends.
1485  * XML_Char is UTF8.
1486  * @param userData: the xml_data structure
1487  * @param name: the tag that ends.
1488  */
1489 static void
1490 xml_endelem(void *userData, const XML_Char *name)
1491 {
1492 	struct xml_data* data = (struct xml_data*)userData;
1493 	if(verb>=4) printf("xml tag end   '%s'\n", name);
1494 	free(data->tag);
1495 	data->tag = NULL;
1496 	if(strcasecmp(name, "KeyDigest") == 0) {
1497 		if(data->use_key)
1498 			xml_append_ds(data);
1499 		data->use_key = 0;
1500 	} else if(strcasecmp(name, "Zone") == 0) {
1501 		if(!xml_is_zone_name(data->czone, ".")) {
1502 			if(verb) printf("xml not for the right zone\n");
1503 			exit(0);
1504 		}
1505 	}
1506 }
1507 
1508 /* Stop the parser when an entity declaration is encountered. For safety. */
1509 static void
1510 xml_entitydeclhandler(void *userData,
1511 	const XML_Char *ATTR_UNUSED(entityName),
1512 	int ATTR_UNUSED(is_parameter_entity),
1513 	const XML_Char *ATTR_UNUSED(value), int ATTR_UNUSED(value_length),
1514 	const XML_Char *ATTR_UNUSED(base),
1515 	const XML_Char *ATTR_UNUSED(systemId),
1516 	const XML_Char *ATTR_UNUSED(publicId),
1517 	const XML_Char *ATTR_UNUSED(notationName))
1518 {
1519 	(void)XML_StopParser((XML_Parser)userData, XML_FALSE);
1520 }
1521 
1522 /**
1523  * XML parser setup of the callbacks for the tags
1524  */
1525 static void
1526 xml_parse_setup(XML_Parser parser, struct xml_data* data, time_t now)
1527 {
1528 	char buf[1024];
1529 	memset(data, 0, sizeof(*data));
1530 	XML_SetUserData(parser, data);
1531 	data->parser = parser;
1532 	data->date = now;
1533 	data->ds = BIO_new(BIO_s_mem());
1534 	data->ctag = BIO_new(BIO_s_mem());
1535 	data->czone = BIO_new(BIO_s_mem());
1536 	data->calgo = BIO_new(BIO_s_mem());
1537 	data->cdigtype = BIO_new(BIO_s_mem());
1538 	data->cdigest = BIO_new(BIO_s_mem());
1539 	if(!data->ds || !data->ctag || !data->calgo || !data->czone ||
1540 		!data->cdigtype || !data->cdigest) {
1541 		if(verb) printf("out of memory\n");
1542 		exit(0);
1543 	}
1544 	snprintf(buf, sizeof(buf), "; created by unbound-anchor on %s",
1545 		ctime(&now));
1546 	if(BIO_write(data->ds, buf, (int)strlen(buf)) < 0) {
1547 		if(verb) printf("out of memory\n");
1548 		exit(0);
1549 	}
1550 	XML_SetEntityDeclHandler(parser, xml_entitydeclhandler);
1551 	XML_SetElementHandler(parser, xml_startelem, xml_endelem);
1552 	XML_SetCharacterDataHandler(parser, xml_charhandle);
1553 }
1554 
1555 /**
1556  * Perform XML parsing of the root-anchors file
1557  * Its format description can be read here
1558  * https://data.iana.org/root-anchors/draft-icann-dnssec-trust-anchor.txt
1559  * It uses libexpat.
1560  * @param xml: BIO with xml data.
1561  * @param now: the current time for checking DS validity periods.
1562  * @return memoryBIO with the DS data in zone format.
1563  * 	or NULL if the zone is insecure.
1564  * 	(It exit()s on error)
1565  */
1566 static BIO*
1567 xml_parse(BIO* xml, time_t now)
1568 {
1569 	char* pp;
1570 	int len;
1571 	XML_Parser parser;
1572 	struct xml_data data;
1573 
1574 	parser = XML_ParserCreate(NULL);
1575 	if(!parser) {
1576 		if(verb) printf("could not XML_ParserCreate\n");
1577 		exit(0);
1578 	}
1579 
1580 	/* setup callbacks */
1581 	xml_parse_setup(parser, &data, now);
1582 
1583 	/* parse it */
1584 	(void)BIO_reset(xml);
1585 	len = (int)BIO_get_mem_data(xml, &pp);
1586 	if(!len || !pp) {
1587 		if(verb) printf("out of memory\n");
1588 		exit(0);
1589 	}
1590 	if(!XML_Parse(parser, pp, len, 1 /*isfinal*/ )) {
1591 		const char *e = XML_ErrorString(XML_GetErrorCode(parser));
1592 		if(verb) printf("XML_Parse failure %s\n", e?e:"");
1593 		exit(0);
1594 	}
1595 
1596 	/* parsed */
1597 	if(verb) printf("XML was parsed successfully, %d keys\n",
1598 			data.num_keys);
1599 	free(data.tag);
1600 	XML_ParserFree(parser);
1601 
1602 	if(verb >= 4) {
1603 		(void)BIO_seek(data.ds, 0);
1604 		len = BIO_get_mem_data(data.ds, &pp);
1605 		printf("got DS bio %d: '", len);
1606 		if(!fwrite(pp, (size_t)len, 1, stdout))
1607 			/* compilers do not allow us to ignore fwrite .. */
1608 			fprintf(stderr, "error writing to stdout\n");
1609 		printf("'\n");
1610 	}
1611 	BIO_free(data.czone);
1612 	BIO_free(data.ctag);
1613 	BIO_free(data.calgo);
1614 	BIO_free(data.cdigtype);
1615 	BIO_free(data.cdigest);
1616 
1617 	if(data.num_keys == 0) {
1618 		/* the root zone seems to have gone insecure */
1619 		BIO_free(data.ds);
1620 		return NULL;
1621 	} else {
1622 		return data.ds;
1623 	}
1624 }
1625 
1626 /* get key usage out of its extension, returns 0 if no key_usage extension */
1627 static unsigned long
1628 get_usage_of_ex(X509* cert)
1629 {
1630 	unsigned long val = 0;
1631 	ASN1_BIT_STRING* s;
1632 	if((s=X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL))) {
1633 		if(s->length > 0) {
1634 			val = s->data[0];
1635 			if(s->length > 1)
1636 				val |= s->data[1] << 8;
1637 		}
1638 		ASN1_BIT_STRING_free(s);
1639 	}
1640 	return val;
1641 }
1642 
1643 /** get valid signers from the list of signers in the signature */
1644 static STACK_OF(X509)*
1645 get_valid_signers(PKCS7* p7, const char* p7signer)
1646 {
1647 	int i;
1648 	STACK_OF(X509)* validsigners = sk_X509_new_null();
1649 	STACK_OF(X509)* signers = PKCS7_get0_signers(p7, NULL, 0);
1650 	unsigned long usage = 0;
1651 	if(!validsigners) {
1652 		if(verb) printf("out of memory\n");
1653 		sk_X509_free(signers);
1654 		return NULL;
1655 	}
1656 	if(!signers) {
1657 		if(verb) printf("no signers in pkcs7 signature\n");
1658 		sk_X509_free(validsigners);
1659 		return NULL;
1660 	}
1661 	for(i=0; i<sk_X509_num(signers); i++) {
1662 		X509_NAME* nm = X509_get_subject_name(
1663 			sk_X509_value(signers, i));
1664 		char buf[1024];
1665 		if(!nm) {
1666 			if(verb) printf("signer %d: cert has no subject name\n", i);
1667 			continue;
1668 		}
1669 		if(verb && nm) {
1670 			char* nmline = X509_NAME_oneline(nm, buf,
1671 				(int)sizeof(buf));
1672 			printf("signer %d: Subject: %s\n", i,
1673 				nmline?nmline:"no subject");
1674 			if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1675 				NID_commonName, buf, (int)sizeof(buf)))
1676 				printf("commonName: %s\n", buf);
1677 			if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1678 				NID_pkcs9_emailAddress, buf, (int)sizeof(buf)))
1679 				printf("emailAddress: %s\n", buf);
1680 		}
1681 		if(verb) {
1682 			int ku_loc = X509_get_ext_by_NID(
1683 				sk_X509_value(signers, i), NID_key_usage, -1);
1684 			if(verb >= 3 && ku_loc >= 0) {
1685 				X509_EXTENSION *ex = X509_get_ext(
1686 					sk_X509_value(signers, i), ku_loc);
1687 				if(ex) {
1688 					printf("keyUsage: ");
1689 					X509V3_EXT_print_fp(stdout, ex, 0, 0);
1690 					printf("\n");
1691 				}
1692 			}
1693 		}
1694 		if(!p7signer || strcmp(p7signer, "")==0) {
1695 			/* there is no name to check, return all records */
1696 			if(verb) printf("did not check commonName of signer\n");
1697 		} else {
1698 			if(!X509_NAME_get_text_by_NID(nm,
1699 				NID_pkcs9_emailAddress,
1700 				buf, (int)sizeof(buf))) {
1701 				if(verb) printf("removed cert with no name\n");
1702 				continue; /* no name, no use */
1703 			}
1704 			if(strcmp(buf, p7signer) != 0) {
1705 				if(verb) printf("removed cert with wrong name\n");
1706 				continue; /* wrong name, skip it */
1707 			}
1708 		}
1709 
1710 		/* check that the key usage allows digital signatures
1711 		 * (the p7s) */
1712 		usage = get_usage_of_ex(sk_X509_value(signers, i));
1713 		if(!(usage & KU_DIGITAL_SIGNATURE)) {
1714 			if(verb) printf("removed cert with no key usage Digital Signature allowed\n");
1715 			continue;
1716 		}
1717 
1718 		/* we like this cert, add it to our list of valid
1719 		 * signers certificates */
1720 		sk_X509_push(validsigners, sk_X509_value(signers, i));
1721 	}
1722 	sk_X509_free(signers);
1723 	return validsigners;
1724 }
1725 
1726 /** verify a PKCS7 signature, false on failure */
1727 static int
1728 verify_p7sig(BIO* data, BIO* p7s, STACK_OF(X509)* trust, const char* p7signer)
1729 {
1730 	PKCS7* p7;
1731 	X509_STORE *store = X509_STORE_new();
1732 	STACK_OF(X509)* validsigners;
1733 	int secure = 0;
1734 	int i;
1735 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1736 	X509_VERIFY_PARAM* param = X509_VERIFY_PARAM_new();
1737 	if(!param) {
1738 		if(verb) printf("out of memory\n");
1739 		X509_STORE_free(store);
1740 		return 0;
1741 	}
1742 	/* do the selfcheck on the root certificate; it checks that the
1743 	 * input is valid */
1744 	X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CHECK_SS_SIGNATURE);
1745 	if(store) X509_STORE_set1_param(store, param);
1746 #endif
1747 	if(!store) {
1748 		if(verb) printf("out of memory\n");
1749 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1750 		X509_VERIFY_PARAM_free(param);
1751 #endif
1752 		return 0;
1753 	}
1754 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1755 	X509_VERIFY_PARAM_free(param);
1756 #endif
1757 
1758 	(void)BIO_reset(p7s);
1759 	(void)BIO_reset(data);
1760 
1761 	/* convert p7s to p7 (the signature) */
1762 	p7 = d2i_PKCS7_bio(p7s, NULL);
1763 	if(!p7) {
1764 		if(verb) printf("could not parse p7s signature file\n");
1765 		X509_STORE_free(store);
1766 		return 0;
1767 	}
1768 	if(verb >= 2) printf("parsed the PKCS7 signature\n");
1769 
1770 	/* convert trust to trusted certificate store */
1771 	for(i=0; i<sk_X509_num(trust); i++) {
1772 		if(!X509_STORE_add_cert(store, sk_X509_value(trust, i))) {
1773 			if(verb) printf("failed X509_STORE_add_cert\n");
1774 			X509_STORE_free(store);
1775 			PKCS7_free(p7);
1776 			return 0;
1777 		}
1778 	}
1779 	if(verb >= 2) printf("setup the X509_STORE\n");
1780 
1781 	/* check what is in the Subject name of the certificates,
1782 	 * and build a stack that contains only the right certificates */
1783 	validsigners = get_valid_signers(p7, p7signer);
1784 	if(!validsigners) {
1785 			X509_STORE_free(store);
1786 			PKCS7_free(p7);
1787 			return 0;
1788 	}
1789 	if(PKCS7_verify(p7, validsigners, store, data, NULL, PKCS7_NOINTERN) == 1) {
1790 		secure = 1;
1791 		if(verb) printf("the PKCS7 signature verified\n");
1792 	} else {
1793 		if(verb) {
1794 			ERR_print_errors_fp(stdout);
1795 		}
1796 	}
1797 
1798 	sk_X509_free(validsigners);
1799 	X509_STORE_free(store);
1800 	PKCS7_free(p7);
1801 	return secure;
1802 }
1803 
1804 /** write unsigned root anchor file, a 5011 revoked tp */
1805 static void
1806 write_unsigned_root(const char* root_anchor_file)
1807 {
1808 	FILE* out;
1809 	time_t now = time(NULL);
1810 	out = fopen(root_anchor_file, "w");
1811 	if(!out) {
1812 		if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1813 		return;
1814 	}
1815 	if(fprintf(out, "; autotrust trust anchor file\n"
1816 		";;REVOKED\n"
1817 		";;id: . 1\n"
1818 		"; This file was written by unbound-anchor on %s"
1819 		"; It indicates that the root does not use DNSSEC\n"
1820 		"; to restart DNSSEC overwrite this file with a\n"
1821 		"; valid trustanchor or (empty-it and run unbound-anchor)\n"
1822 		, ctime(&now)) < 0) {
1823 		if(verb) printf("failed to write 'unsigned' to %s\n",
1824 			root_anchor_file);
1825 		if(verb && errno != 0) printf("%s\n", strerror(errno));
1826 	}
1827 	fclose(out);
1828 }
1829 
1830 /** write root anchor file */
1831 static void
1832 write_root_anchor(const char* root_anchor_file, BIO* ds)
1833 {
1834 	char* pp = NULL;
1835 	int len;
1836 	FILE* out;
1837 	(void)BIO_seek(ds, 0);
1838 	len = BIO_get_mem_data(ds, &pp);
1839 	if(!len || !pp) {
1840 		if(verb) printf("out of memory\n");
1841 		return;
1842 	}
1843 	out = fopen(root_anchor_file, "w");
1844 	if(!out) {
1845 		if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1846 		return;
1847 	}
1848 	if(fwrite(pp, (size_t)len, 1, out) != 1) {
1849 		if(verb) printf("failed to write all data to %s\n",
1850 			root_anchor_file);
1851 		if(verb && errno != 0) printf("%s\n", strerror(errno));
1852 	}
1853 	fclose(out);
1854 }
1855 
1856 /** Perform the verification and update of the trustanchor file */
1857 static void
1858 verify_and_update_anchor(const char* root_anchor_file, BIO* xml, BIO* p7s,
1859 	STACK_OF(X509)* cert, const char* p7signer)
1860 {
1861 	BIO* ds;
1862 
1863 	/* verify xml file */
1864 	if(!verify_p7sig(xml, p7s, cert, p7signer)) {
1865 		printf("the PKCS7 signature failed\n");
1866 		exit(0);
1867 	}
1868 
1869 	/* parse the xml file into DS records */
1870 	ds = xml_parse(xml, time(NULL));
1871 	if(!ds) {
1872 		/* the root zone is unsigned now */
1873 		write_unsigned_root(root_anchor_file);
1874 	} else {
1875 		/* reinstate 5011 tracking */
1876 		write_root_anchor(root_anchor_file, ds);
1877 	}
1878 	BIO_free(ds);
1879 }
1880 
1881 #ifdef USE_WINSOCK
1882 static void do_wsa_cleanup(void) { WSACleanup(); }
1883 #endif
1884 
1885 /** perform actual certupdate work */
1886 static int
1887 do_certupdate(const char* root_anchor_file, const char* root_cert_file,
1888 	const char* urlname, const char* xmlname, const char* p7sname,
1889 	const char* p7signer, const char* res_conf, const char* root_hints,
1890 	const char* debugconf, int ip4only, int ip6only, int port,
1891 	struct ub_result* dnskey)
1892 {
1893 	STACK_OF(X509)* cert;
1894 	BIO *xml, *p7s;
1895 	struct ip_list* ip_list = NULL;
1896 
1897 	/* read pem file or provide builtin */
1898 	cert = read_cert_or_builtin(root_cert_file);
1899 
1900 	/* lookup A, AAAA for the urlname (or parse urlname if IP address) */
1901 	ip_list = resolve_name(urlname, port, res_conf, root_hints, debugconf,
1902 		ip4only, ip6only);
1903 
1904 #ifdef USE_WINSOCK
1905 	if(1) { /* libunbound finished, startup WSA for the https connection */
1906 		WSADATA wsa_data;
1907 		int r;
1908 		if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
1909 			if(verb) printf("WSAStartup failed: %s\n",
1910 				wsa_strerror(r));
1911 			exit(0);
1912 		}
1913 		atexit(&do_wsa_cleanup);
1914 	}
1915 #endif
1916 
1917 	/* fetch the necessary files over HTTPS */
1918 	xml = https(ip_list, xmlname, urlname);
1919 	p7s = https(ip_list, p7sname, urlname);
1920 
1921 	/* verify and update the root anchor */
1922 	verify_and_update_anchor(root_anchor_file, xml, p7s, cert, p7signer);
1923 	if(verb) printf("success: the anchor has been updated "
1924 			"using the cert\n");
1925 
1926 	free_file_bio(xml);
1927 	free_file_bio(p7s);
1928 #ifndef S_SPLINT_S
1929 	sk_X509_pop_free(cert, X509_free);
1930 #endif
1931 	ub_resolve_free(dnskey);
1932 	ip_list_free(ip_list);
1933 	return 1;
1934 }
1935 
1936 /**
1937  * Try to read the root RFC5011 autotrust anchor file,
1938  * @param file: filename.
1939  * @return:
1940  * 	0 if does not exist or empty
1941  * 	1 if trust-point-revoked-5011
1942  * 	2 if it is OK.
1943  */
1944 static int
1945 try_read_anchor(const char* file)
1946 {
1947 	int empty = 1;
1948 	char line[10240];
1949 	char* p;
1950 	FILE* in = fopen(file, "r");
1951 	if(!in) {
1952 		/* only if the file does not exist, can we fix it */
1953 		if(errno != ENOENT) {
1954 			if(verb) printf("%s: %s\n", file, strerror(errno));
1955 			if(verb) printf("error: cannot access the file\n");
1956 			exit(0);
1957 		}
1958 		if(verb) printf("%s does not exist\n", file);
1959 		return 0;
1960 	}
1961 	while(fgets(line, (int)sizeof(line), in)) {
1962 		line[sizeof(line)-1] = 0;
1963 		if(strncmp(line, ";;REVOKED", 9) == 0) {
1964 			fclose(in);
1965 			if(verb) printf("%s : the trust point is revoked\n"
1966 				"and the zone is considered unsigned.\n"
1967 				"if you wish to re-enable, delete the file\n",
1968 				file);
1969 			return 1;
1970 		}
1971 		p=line;
1972 		while(*p == ' ' || *p == '\t')
1973 			p++;
1974 		if(p[0]==0 || p[0]=='\n' || p[0]==';') continue;
1975 		/* this line is a line of content */
1976 		empty = 0;
1977 	}
1978 	fclose(in);
1979 	if(empty) {
1980 		if(verb) printf("%s is empty\n", file);
1981 		return 0;
1982 	}
1983 	if(verb) printf("%s has content\n", file);
1984 	return 2;
1985 }
1986 
1987 /** Write the builtin root anchor to a file */
1988 static void
1989 write_builtin_anchor(const char* file)
1990 {
1991 	const char* builtin_root_anchor = get_builtin_ds();
1992 	FILE* out = fopen(file, "w");
1993 	if(!out) {
1994 		if(verb) printf("%s: %s\n", file, strerror(errno));
1995 		if(verb) printf("  could not write builtin anchor\n");
1996 		return;
1997 	}
1998 	if(!fwrite(builtin_root_anchor, strlen(builtin_root_anchor), 1, out)) {
1999 		if(verb) printf("%s: %s\n", file, strerror(errno));
2000 		if(verb) printf("  could not complete write builtin anchor\n");
2001 	}
2002 	fclose(out);
2003 }
2004 
2005 /**
2006  * Check the root anchor file.
2007  * If does not exist, provide builtin and write file.
2008  * If empty, provide builtin and write file.
2009  * If trust-point-revoked-5011 file: make the program exit.
2010  * @param root_anchor_file: filename of the root anchor.
2011  * @param used_builtin: set to 1 if the builtin is written.
2012  * @return 0 if trustpoint is insecure, 1 on success.  Exit on failure.
2013  */
2014 static int
2015 provide_builtin(const char* root_anchor_file, int* used_builtin)
2016 {
2017 	/* try to read it */
2018 	switch(try_read_anchor(root_anchor_file))
2019 	{
2020 		case 0: /* no exist or empty */
2021 			write_builtin_anchor(root_anchor_file);
2022 			*used_builtin = 1;
2023 			break;
2024 		case 1: /* revoked tp */
2025 			return 0;
2026 		case 2: /* it is fine */
2027 		default:
2028 			break;
2029 	}
2030 	return 1;
2031 }
2032 
2033 /**
2034  * add an autotrust anchor for the root to the context
2035  */
2036 static void
2037 add_5011_probe_root(struct ub_ctx* ctx, const char* root_anchor_file)
2038 {
2039 	int r;
2040 	r = ub_ctx_set_option(ctx, "auto-trust-anchor-file:", root_anchor_file);
2041 	if(r) {
2042 		if(verb) printf("add 5011 probe to ctx: %s\n", ub_strerror(r));
2043 		ub_ctx_delete(ctx);
2044 		exit(0);
2045 	}
2046 }
2047 
2048 /**
2049  * Prime the root key and return the result.  Exit on error.
2050  * @param ctx: the unbound context to perform the priming with.
2051  * @return: the result of the prime, on error it exit()s.
2052  */
2053 static struct ub_result*
2054 prime_root_key(struct ub_ctx* ctx)
2055 {
2056 	struct ub_result* res = NULL;
2057 	int r;
2058 	r = ub_resolve(ctx, ".", LDNS_RR_TYPE_DNSKEY, LDNS_RR_CLASS_IN, &res);
2059 	if(r) {
2060 		if(verb) printf("resolve DNSKEY: %s\n", ub_strerror(r));
2061 		ub_ctx_delete(ctx);
2062 		exit(0);
2063 	}
2064 	if(!res) {
2065 		if(verb) printf("out of memory\n");
2066 		ub_ctx_delete(ctx);
2067 		exit(0);
2068 	}
2069 	return res;
2070 }
2071 
2072 /** see if ADDPEND keys exist in autotrust file (if possible) */
2073 static int
2074 read_if_pending_keys(const char* file)
2075 {
2076 	FILE* in = fopen(file, "r");
2077 	char line[8192];
2078 	if(!in) {
2079 		if(verb>=2) printf("%s: %s\n", file, strerror(errno));
2080 		return 0;
2081 	}
2082 	while(fgets(line, (int)sizeof(line), in)) {
2083 		if(line[0]==';') continue;
2084 		if(strstr(line, "[ ADDPEND ]")) {
2085 			fclose(in);
2086 			if(verb) printf("RFC5011-state has ADDPEND keys\n");
2087 			return 1;
2088 		}
2089 	}
2090 	fclose(in);
2091 	return 0;
2092 }
2093 
2094 /** read last successful probe time from autotrust file (if possible) */
2095 static int32_t
2096 read_last_success_time(const char* file)
2097 {
2098 	FILE* in = fopen(file, "r");
2099 	char line[1024];
2100 	if(!in) {
2101 		if(verb) printf("%s: %s\n", file, strerror(errno));
2102 		return 0;
2103 	}
2104 	while(fgets(line, (int)sizeof(line), in)) {
2105 		if(strncmp(line, ";;last_success: ", 16) == 0) {
2106 			char* e;
2107 			time_t x = (unsigned int)strtol(line+16, &e, 10);
2108 			fclose(in);
2109 			if(line+16 == e) {
2110 				if(verb) printf("failed to parse "
2111 					"last_success probe time\n");
2112 				return 0;
2113 			}
2114 			if(verb) printf("last successful probe: %s", ctime(&x));
2115 			return (int32_t)x;
2116 		}
2117 	}
2118 	fclose(in);
2119 	if(verb) printf("no last_success probe time in anchor file\n");
2120 	return 0;
2121 }
2122 
2123 /**
2124  * Read autotrust 5011 probe file and see if the date
2125  * compared to the current date allows a certupdate.
2126  * If the last successful probe was recent then 5011 cannot be behind,
2127  * and the failure cannot be solved with a certupdate.
2128  * The debugconf is to validation-override the date for testing.
2129  * @param root_anchor_file: filename of root key
2130  * @return true if certupdate is ok.
2131  */
2132 static int
2133 probe_date_allows_certupdate(const char* root_anchor_file)
2134 {
2135 	int has_pending_keys = read_if_pending_keys(root_anchor_file);
2136 	int32_t last_success = read_last_success_time(root_anchor_file);
2137 	int32_t now = (int32_t)time(NULL);
2138 	int32_t leeway = 30 * 24 * 3600; /* 30 days leeway */
2139 	/* if the date is before 2010-07-15:00.00.00 then the root has not
2140 	 * been signed yet, and thus we refuse to take action. */
2141 	if(time(NULL) < xml_convertdate("2010-07-15T00:00:00")) {
2142 		if(verb) printf("the date is before the root was first signed,"
2143 			" please correct the clock\n");
2144 		return 0;
2145 	}
2146 	if(last_success == 0)
2147 		return 1; /* no probe time */
2148 	if(has_pending_keys)
2149 		return 1; /* key in ADDPEND state, a previous probe has
2150 		inserted that, and it was present in all recent probes,
2151 		but it has not become active.  The 30 day timer may not have
2152 		expired, but we know(for sure) there is a rollover going on.
2153 		If we only managed to pickup the new key on its last day
2154 		of announcement (for example) this can happen. */
2155 	if(now - last_success < 0) {
2156 		if(verb) printf("the last successful probe is in the future,"
2157 			" clock was modified\n");
2158 		return 0;
2159 	}
2160 	if(now - last_success >= leeway) {
2161 		if(verb) printf("the last successful probe was more than 30 "
2162 			"days ago\n");
2163 		return 1;
2164 	}
2165 	if(verb) printf("the last successful probe is recent\n");
2166 	return 0;
2167 }
2168 
2169 /** perform the unbound-anchor work */
2170 static int
2171 do_root_update_work(const char* root_anchor_file, const char* root_cert_file,
2172 	const char* urlname, const char* xmlname, const char* p7sname,
2173 	const char* p7signer, const char* res_conf, const char* root_hints,
2174 	const char* debugconf, int ip4only, int ip6only, int force, int port)
2175 {
2176 	struct ub_ctx* ctx;
2177 	struct ub_result* dnskey;
2178 	int used_builtin = 0;
2179 
2180 	/* see if builtin rootanchor needs to be provided, or if
2181 	 * rootanchor is 'revoked-trust-point' */
2182 	if(!provide_builtin(root_anchor_file, &used_builtin))
2183 		return 0;
2184 
2185 	/* make unbound context with 5011-probe for root anchor,
2186 	 * and probe . DNSKEY */
2187 	ctx = create_unbound_context(res_conf, root_hints, debugconf,
2188 		ip4only, ip6only);
2189 	add_5011_probe_root(ctx, root_anchor_file);
2190 	dnskey = prime_root_key(ctx);
2191 	ub_ctx_delete(ctx);
2192 
2193 	/* if secure: exit */
2194 	if(dnskey->secure && !force) {
2195 		if(verb) printf("success: the anchor is ok\n");
2196 		ub_resolve_free(dnskey);
2197 		return used_builtin;
2198 	}
2199 	if(force && verb) printf("debug cert update forced\n");
2200 
2201 	/* if not (and NOERROR): check date and do certupdate */
2202 	if((dnskey->rcode == 0 &&
2203 		probe_date_allows_certupdate(root_anchor_file)) || force) {
2204 		if(do_certupdate(root_anchor_file, root_cert_file, urlname,
2205 			xmlname, p7sname, p7signer, res_conf, root_hints,
2206 			debugconf, ip4only, ip6only, port, dnskey))
2207 			return 1;
2208 		return used_builtin;
2209 	}
2210 	if(verb) printf("fail: the anchor is NOT ok and could not be fixed\n");
2211 	ub_resolve_free(dnskey);
2212 	return used_builtin;
2213 }
2214 
2215 /** getopt global, in case header files fail to declare it. */
2216 extern int optind;
2217 /** getopt global, in case header files fail to declare it. */
2218 extern char* optarg;
2219 
2220 /** Main routine for unbound-anchor */
2221 int main(int argc, char* argv[])
2222 {
2223 	int c;
2224 	const char* root_anchor_file = ROOT_ANCHOR_FILE;
2225 	const char* root_cert_file = ROOT_CERT_FILE;
2226 	const char* urlname = URLNAME;
2227 	const char* xmlname = XMLNAME;
2228 	const char* p7sname = P7SNAME;
2229 	const char* p7signer = P7SIGNER;
2230 	const char* res_conf = NULL;
2231 	const char* root_hints = NULL;
2232 	const char* debugconf = NULL;
2233 	int dolist=0, ip4only=0, ip6only=0, force=0, port = HTTPS_PORT;
2234 	/* parse the options */
2235 	while( (c=getopt(argc, argv, "46C:FP:a:c:f:hln:r:s:u:vx:")) != -1) {
2236 		switch(c) {
2237 		case 'l':
2238 			dolist = 1;
2239 			break;
2240 		case '4':
2241 			ip4only = 1;
2242 			break;
2243 		case '6':
2244 			ip6only = 1;
2245 			break;
2246 		case 'a':
2247 			root_anchor_file = optarg;
2248 			break;
2249 		case 'c':
2250 			root_cert_file = optarg;
2251 			break;
2252 		case 'u':
2253 			urlname = optarg;
2254 			break;
2255 		case 'x':
2256 			xmlname = optarg;
2257 			break;
2258 		case 's':
2259 			p7sname = optarg;
2260 			break;
2261 		case 'n':
2262 			p7signer = optarg;
2263 			break;
2264 		case 'f':
2265 			res_conf = optarg;
2266 			break;
2267 		case 'r':
2268 			root_hints = optarg;
2269 			break;
2270 		case 'C':
2271 			debugconf = optarg;
2272 			break;
2273 		case 'F':
2274 			force = 1;
2275 			break;
2276 		case 'P':
2277 			port = atoi(optarg);
2278 			break;
2279 		case 'v':
2280 			verb++;
2281 			break;
2282 		case '?':
2283 		case 'h':
2284 		default:
2285 			usage();
2286 		}
2287 	}
2288 	argc -= optind;
2289 	argv += optind;
2290 	if(argc != 0)
2291 		usage();
2292 
2293 	ERR_load_crypto_strings();
2294 	ERR_load_SSL_strings();
2295 	OpenSSL_add_all_algorithms();
2296 	(void)SSL_library_init();
2297 
2298 	if(dolist) do_list_builtin();
2299 
2300 	return do_root_update_work(root_anchor_file, root_cert_file, urlname,
2301 		xmlname, p7sname, p7signer, res_conf, root_hints, debugconf,
2302 		ip4only, ip6only, force, port);
2303 }
2304