xref: /freebsd/contrib/unbound/smallapp/unbound-anchor.c (revision 864c53ead899f7838cd2e1cca3b485a4a82f5cdc)
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 static int get_random(void)
671 {
672 	int r;
673 	if (RAND_bytes((unsigned char*)&r, (int)sizeof(r)) == 1) {
674 		return r;
675 	}
676 	return (int)random();
677 }
678 
679 /** pick random unused element from IP list */
680 static struct ip_list*
681 pick_random_ip(struct ip_list* list)
682 {
683 	struct ip_list* p = list;
684 	int num = count_unused(list);
685 	int sel;
686 	if(num == 0) return NULL;
687 	/* not perfect, but random enough */
688 	sel = get_random() % num;
689 	/* skip over unused elements that we did not select */
690 	while(sel > 0 && p) {
691 		if(!p->used) sel--;
692 		p = p->next;
693 	}
694 	/* find the next unused element */
695 	while(p && p->used)
696 		p = p->next;
697 	if(!p) return NULL; /* robustness */
698 	return p;
699 }
700 
701 /** close the fd */
702 static void
703 fd_close(int fd)
704 {
705 #ifndef USE_WINSOCK
706 	close(fd);
707 #else
708 	closesocket(fd);
709 #endif
710 }
711 
712 /** printout socket errno */
713 static void
714 print_sock_err(const char* msg)
715 {
716 #ifndef USE_WINSOCK
717 	if(verb) printf("%s: %s\n", msg, strerror(errno));
718 #else
719 	if(verb) printf("%s: %s\n", msg, wsa_strerror(WSAGetLastError()));
720 #endif
721 }
722 
723 /** connect to IP address */
724 static int
725 connect_to_ip(struct ip_list* ip)
726 {
727 	int fd;
728 	verb_addr("connect to", ip);
729 	fd = socket(ip->len==(socklen_t)sizeof(struct sockaddr_in)?
730 		AF_INET:AF_INET6, SOCK_STREAM, 0);
731 	if(fd == -1) {
732 		print_sock_err("socket");
733 		return -1;
734 	}
735 	if(connect(fd, (struct sockaddr*)&ip->addr, ip->len) < 0) {
736 		print_sock_err("connect");
737 		fd_close(fd);
738 		return -1;
739 	}
740 	return fd;
741 }
742 
743 /** create SSL context */
744 static SSL_CTX*
745 setup_sslctx(void)
746 {
747 	SSL_CTX* sslctx = SSL_CTX_new(SSLv23_client_method());
748 	if(!sslctx) {
749 		if(verb) printf("SSL_CTX_new error\n");
750 		return NULL;
751 	}
752 	return sslctx;
753 }
754 
755 /** initiate TLS on a connection */
756 static SSL*
757 TLS_initiate(SSL_CTX* sslctx, int fd)
758 {
759 	X509* x;
760 	int r;
761 	SSL* ssl = SSL_new(sslctx);
762 	if(!ssl) {
763 		if(verb) printf("SSL_new error\n");
764 		return NULL;
765 	}
766 	SSL_set_connect_state(ssl);
767 	(void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
768 	if(!SSL_set_fd(ssl, fd)) {
769 		if(verb) printf("SSL_set_fd error\n");
770 		SSL_free(ssl);
771 		return NULL;
772 	}
773 	while(1) {
774 		ERR_clear_error();
775 		if( (r=SSL_do_handshake(ssl)) == 1)
776 			break;
777 		r = SSL_get_error(ssl, r);
778 		if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) {
779 			if(verb) printf("SSL handshake failed\n");
780 			SSL_free(ssl);
781 			return NULL;
782 		}
783 		/* wants to be called again */
784 	}
785 	x = SSL_get_peer_certificate(ssl);
786 	if(!x) {
787 		if(verb) printf("Server presented no peer certificate\n");
788 		SSL_free(ssl);
789 		return NULL;
790 	}
791 	verb_cert("server SSL certificate", x);
792 	X509_free(x);
793 	return ssl;
794 }
795 
796 /** perform neat TLS shutdown */
797 static void
798 TLS_shutdown(int fd, SSL* ssl, SSL_CTX* sslctx)
799 {
800 	/* shutdown the SSL connection nicely */
801 	if(SSL_shutdown(ssl) == 0) {
802 		SSL_shutdown(ssl);
803 	}
804 	SSL_free(ssl);
805 	SSL_CTX_free(sslctx);
806 	fd_close(fd);
807 }
808 
809 /** write a line over SSL */
810 static int
811 write_ssl_line(SSL* ssl, const char* str, const char* sec)
812 {
813 	char buf[1024];
814 	size_t l;
815 	if(sec) {
816 		snprintf(buf, sizeof(buf), str, sec);
817 	} else {
818 		snprintf(buf, sizeof(buf), "%s", str);
819 	}
820 	l = strlen(buf);
821 	if(l+2 >= sizeof(buf)) {
822 		if(verb) printf("line too long\n");
823 		return 0;
824 	}
825 	if(verb >= 2) printf("SSL_write: %s\n", buf);
826 	buf[l] = '\r';
827 	buf[l+1] = '\n';
828 	buf[l+2] = 0;
829 	/* add \r\n */
830 	if(SSL_write(ssl, buf, (int)strlen(buf)) <= 0) {
831 		if(verb) printf("could not SSL_write %s", str);
832 		return 0;
833 	}
834 	return 1;
835 }
836 
837 /** process header line, check rcode and keeping track of size */
838 static int
839 process_one_header(char* buf, size_t* clen, int* chunked)
840 {
841 	if(verb>=2) printf("header: '%s'\n", buf);
842 	if(strncasecmp(buf, "HTTP/1.1 ", 9) == 0) {
843 		/* check returncode */
844 		if(buf[9] != '2') {
845 			if(verb) printf("bad status %s\n", buf+9);
846 			return 0;
847 		}
848 	} else if(strncasecmp(buf, "Content-Length: ", 16) == 0) {
849 		if(!*chunked)
850 			*clen = (size_t)atoi(buf+16);
851 	} else if(strncasecmp(buf, "Transfer-Encoding: chunked", 19+7) == 0) {
852 		*clen = 0;
853 		*chunked = 1;
854 	}
855 	return 1;
856 }
857 
858 /**
859  * Read one line from SSL
860  * zero terminates.
861  * skips "\r\n" (but not copied to buf).
862  * @param ssl: the SSL connection to read from (blocking).
863  * @param buf: buffer to return line in.
864  * @param len: size of the buffer.
865  * @return 0 on error, 1 on success.
866  */
867 static int
868 read_ssl_line(SSL* ssl, char* buf, size_t len)
869 {
870 	size_t n = 0;
871 	int r;
872 	int endnl = 0;
873 	while(1) {
874 		if(n >= len) {
875 			if(verb) printf("line too long\n");
876 			return 0;
877 		}
878 		if((r = SSL_read(ssl, buf+n, 1)) <= 0) {
879 			if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
880 				/* EOF */
881 				break;
882 			}
883 			if(verb) printf("could not SSL_read\n");
884 			return 0;
885 		}
886 		if(endnl && buf[n] == '\n') {
887 			break;
888 		} else if(endnl) {
889 			/* bad data */
890 			if(verb) printf("error: stray linefeeds\n");
891 			return 0;
892 		} else if(buf[n] == '\r') {
893 			/* skip \r, and also \n on the wire */
894 			endnl = 1;
895 			continue;
896 		} else if(buf[n] == '\n') {
897 			/* skip the \n, we are done */
898 			break;
899 		} else n++;
900 	}
901 	buf[n] = 0;
902 	return 1;
903 }
904 
905 /** read http headers and process them */
906 static size_t
907 read_http_headers(SSL* ssl, size_t* clen)
908 {
909 	char buf[1024];
910 	int chunked = 0;
911 	*clen = 0;
912 	while(read_ssl_line(ssl, buf, sizeof(buf))) {
913 		if(buf[0] == 0)
914 			return 1;
915 		if(!process_one_header(buf, clen, &chunked))
916 			return 0;
917 	}
918 	return 0;
919 }
920 
921 /** read a data chunk */
922 static char*
923 read_data_chunk(SSL* ssl, size_t len)
924 {
925 	size_t got = 0;
926 	int r;
927 	char* data = malloc(len+1);
928 	if(!data) {
929 		if(verb) printf("out of memory\n");
930 		return NULL;
931 	}
932 	while(got < len) {
933 		if((r = SSL_read(ssl, data+got, (int)(len-got))) <= 0) {
934 			if(SSL_get_error(ssl, r) == SSL_ERROR_ZERO_RETURN) {
935 				/* EOF */
936 				if(verb) printf("could not SSL_read: unexpected EOF\n");
937 				free(data);
938 				return NULL;
939 			}
940 			if(verb) printf("could not SSL_read\n");
941 			free(data);
942 			return NULL;
943 		}
944 		if(verb >= 2) printf("at %d/%d\n", (int)got, (int)len);
945 		got += r;
946 	}
947 	if(verb>=2) printf("read %d data\n", (int)len);
948 	data[len] = 0;
949 	return data;
950 }
951 
952 /** parse chunk header */
953 static int
954 parse_chunk_header(char* buf, size_t* result)
955 {
956 	char* e = NULL;
957 	size_t v = (size_t)strtol(buf, &e, 16);
958 	if(e == buf)
959 		return 0;
960 	*result = v;
961 	return 1;
962 }
963 
964 /** read chunked data from connection */
965 static BIO*
966 do_chunked_read(SSL* ssl)
967 {
968 	char buf[1024];
969 	size_t len;
970 	char* body;
971 	BIO* mem = BIO_new(BIO_s_mem());
972 	if(verb>=3) printf("do_chunked_read\n");
973 	if(!mem) {
974 		if(verb) printf("out of memory\n");
975 		return NULL;
976 	}
977 	while(read_ssl_line(ssl, buf, sizeof(buf))) {
978 		/* read the chunked start line */
979 		if(verb>=2) printf("chunk header: %s\n", buf);
980 		if(!parse_chunk_header(buf, &len)) {
981 			BIO_free(mem);
982 			if(verb>=3) printf("could not parse chunk header\n");
983 			return NULL;
984 		}
985 		if(verb>=2) printf("chunk len: %d\n", (int)len);
986 		/* are we done? */
987 		if(len == 0) {
988 			char z = 0;
989 			/* skip end-of-chunk-trailer lines,
990 			 * until the empty line after that */
991 			do {
992 				if(!read_ssl_line(ssl, buf, sizeof(buf))) {
993 					BIO_free(mem);
994 					return NULL;
995 				}
996 			} while (strlen(buf) > 0);
997 			/* end of chunks, zero terminate it */
998 			if(BIO_write(mem, &z, 1) <= 0) {
999 				if(verb) printf("out of memory\n");
1000 				BIO_free(mem);
1001 				return NULL;
1002 			}
1003 			return mem;
1004 		}
1005 		/* read the chunked body */
1006 		body = read_data_chunk(ssl, len);
1007 		if(!body) {
1008 			BIO_free(mem);
1009 			return NULL;
1010 		}
1011 		if(BIO_write(mem, body, (int)len) <= 0) {
1012 			if(verb) printf("out of memory\n");
1013 			free(body);
1014 			BIO_free(mem);
1015 			return NULL;
1016 		}
1017 		free(body);
1018 		/* skip empty line after data chunk */
1019 		if(!read_ssl_line(ssl, buf, sizeof(buf))) {
1020 			BIO_free(mem);
1021 			return NULL;
1022 		}
1023 	}
1024 	BIO_free(mem);
1025 	return NULL;
1026 }
1027 
1028 /** start HTTP1.1 transaction on SSL */
1029 static int
1030 write_http_get(SSL* ssl, const char* pathname, const char* urlname)
1031 {
1032 	if(write_ssl_line(ssl, "GET /%s HTTP/1.1", pathname) &&
1033 	   write_ssl_line(ssl, "Host: %s", urlname) &&
1034 	   write_ssl_line(ssl, "User-Agent: unbound-anchor/%s",
1035 	   	PACKAGE_VERSION) &&
1036 	   /* We do not really do multiple queries per connection,
1037 	    * but this header setting is also not needed.
1038 	    * write_ssl_line(ssl, "Connection: close", NULL) &&*/
1039 	   write_ssl_line(ssl, "", NULL)) {
1040 		return 1;
1041 	}
1042 	return 0;
1043 }
1044 
1045 /** read chunked data and zero terminate; len is without zero */
1046 static char*
1047 read_chunked_zero_terminate(SSL* ssl, size_t* len)
1048 {
1049 	/* do the chunked version */
1050 	BIO* tmp = do_chunked_read(ssl);
1051 	char* data, *d = NULL;
1052 	size_t l;
1053 	if(!tmp) {
1054 		if(verb) printf("could not read from https\n");
1055 		return NULL;
1056 	}
1057 	l = (size_t)BIO_get_mem_data(tmp, &d);
1058 	if(verb>=2) printf("chunked data is %d\n", (int)l);
1059 	if(l == 0 || d == NULL) {
1060 		if(verb) printf("out of memory\n");
1061 		return NULL;
1062 	}
1063 	*len = l-1;
1064 	data = (char*)malloc(l);
1065 	if(data == NULL) {
1066 		if(verb) printf("out of memory\n");
1067 		return NULL;
1068 	}
1069 	memcpy(data, d, l);
1070 	BIO_free(tmp);
1071 	return data;
1072 }
1073 
1074 /** read HTTP result from SSL */
1075 static BIO*
1076 read_http_result(SSL* ssl)
1077 {
1078 	size_t len = 0;
1079 	char* data;
1080 	BIO* m;
1081 	if(!read_http_headers(ssl, &len)) {
1082 		return NULL;
1083 	}
1084 	if(len == 0) {
1085 		data = read_chunked_zero_terminate(ssl, &len);
1086 	} else {
1087 		data = read_data_chunk(ssl, len);
1088 	}
1089 	if(!data) return NULL;
1090 	if(verb >= 4) print_data("read data", data, (int)len);
1091 	m = BIO_new_mem_buf(data, (int)len);
1092 	if(!m) {
1093 		if(verb) printf("out of memory\n");
1094 		exit(0);
1095 	}
1096 	return m;
1097 }
1098 
1099 /** https to an IP addr, return BIO with pathname or NULL */
1100 static BIO*
1101 https_to_ip(struct ip_list* ip, const char* pathname, const char* urlname)
1102 {
1103 	int fd;
1104 	SSL* ssl;
1105 	BIO* bio;
1106 	SSL_CTX* sslctx = setup_sslctx();
1107 	if(!sslctx) {
1108 		return NULL;
1109 	}
1110 	fd = connect_to_ip(ip);
1111 	if(fd == -1) {
1112 		SSL_CTX_free(sslctx);
1113 		return NULL;
1114 	}
1115 	ssl = TLS_initiate(sslctx, fd);
1116 	if(!ssl) {
1117 		SSL_CTX_free(sslctx);
1118 		fd_close(fd);
1119 		return NULL;
1120 	}
1121 	if(!write_http_get(ssl, pathname, urlname)) {
1122 		if(verb) printf("could not write to server\n");
1123 		SSL_free(ssl);
1124 		SSL_CTX_free(sslctx);
1125 		fd_close(fd);
1126 		return NULL;
1127 	}
1128 	bio = read_http_result(ssl);
1129 	TLS_shutdown(fd, ssl, sslctx);
1130 	return bio;
1131 }
1132 
1133 /**
1134  * Do a HTTPS, HTTP1.1 over TLS, to fetch a file
1135  * @param ip_list: list of IP addresses to use to fetch from.
1136  * @param pathname: pathname of file on server to GET.
1137  * @param urlname: name to pass as the virtual host for this request.
1138  * @return a memory BIO with the file in it.
1139  */
1140 static BIO*
1141 https(struct ip_list* ip_list, const char* pathname, const char* urlname)
1142 {
1143 	struct ip_list* ip;
1144 	BIO* bio = NULL;
1145 	/* try random address first, and work through the list */
1146 	wipe_ip_usage(ip_list);
1147 	while( (ip = pick_random_ip(ip_list)) ) {
1148 		ip->used = 1;
1149 		bio = https_to_ip(ip, pathname, urlname);
1150 		if(bio) break;
1151 	}
1152 	if(!bio) {
1153 		if(verb) printf("could not fetch %s\n", pathname);
1154 		exit(0);
1155 	} else {
1156 		if(verb) printf("fetched %s (%d bytes)\n",
1157 			pathname, (int)BIO_ctrl_pending(bio));
1158 	}
1159 	return bio;
1160 }
1161 
1162 /** free up a downloaded file BIO */
1163 static void
1164 free_file_bio(BIO* bio)
1165 {
1166 	char* pp = NULL;
1167 	(void)BIO_reset(bio);
1168 	(void)BIO_get_mem_data(bio, &pp);
1169 	free(pp);
1170 	BIO_free(bio);
1171 }
1172 
1173 /** XML parse private data during the parse */
1174 struct xml_data {
1175 	/** the parser, reference */
1176 	XML_Parser parser;
1177 	/** the current tag; malloced; or NULL outside of tags */
1178 	char* tag;
1179 	/** current date to use during the parse */
1180 	time_t date;
1181 	/** number of keys usefully read in */
1182 	int num_keys;
1183 	/** the compiled anchors as DS records */
1184 	BIO* ds;
1185 
1186 	/** do we want to use this anchor? */
1187 	int use_key;
1188 	/** the current anchor: Zone */
1189 	BIO* czone;
1190 	/** the current anchor: KeyTag */
1191 	BIO* ctag;
1192 	/** the current anchor: Algorithm */
1193 	BIO* calgo;
1194 	/** the current anchor: DigestType */
1195 	BIO* cdigtype;
1196 	/** the current anchor: Digest*/
1197 	BIO* cdigest;
1198 };
1199 
1200 /** The BIO for the tag */
1201 static BIO*
1202 xml_selectbio(struct xml_data* data, const char* tag)
1203 {
1204 	BIO* b = NULL;
1205 	if(strcasecmp(tag, "KeyTag") == 0)
1206 		b = data->ctag;
1207 	else if(strcasecmp(tag, "Algorithm") == 0)
1208 		b = data->calgo;
1209 	else if(strcasecmp(tag, "DigestType") == 0)
1210 		b = data->cdigtype;
1211 	else if(strcasecmp(tag, "Digest") == 0)
1212 		b = data->cdigest;
1213 	return b;
1214 }
1215 
1216 /**
1217  * XML handle character data, the data inside an element.
1218  * @param userData: xml_data structure
1219  * @param s: the character data.  May not all be in one callback.
1220  * 	NOT zero terminated.
1221  * @param len: length of this part of the data.
1222  */
1223 static void
1224 xml_charhandle(void *userData, const XML_Char *s, int len)
1225 {
1226 	struct xml_data* data = (struct xml_data*)userData;
1227 	BIO* b = NULL;
1228 	/* skip characters outside of elements */
1229 	if(!data->tag)
1230 		return;
1231 	if(verb>=4) {
1232 		int i;
1233 		printf("%s%s charhandle: '",
1234 			data->use_key?"use ":"",
1235 			data->tag?data->tag:"none");
1236 		for(i=0; i<len; i++)
1237 			printf("%c", s[i]);
1238 		printf("'\n");
1239 	}
1240 	if(strcasecmp(data->tag, "Zone") == 0) {
1241 		if(BIO_write(data->czone, s, len) < 0) {
1242 			if(verb) printf("out of memory in BIO_write\n");
1243 			exit(0);
1244 		}
1245 		return;
1246 	}
1247 	/* only store if key is used */
1248 	if(!data->use_key)
1249 		return;
1250 	b = xml_selectbio(data, data->tag);
1251 	if(b) {
1252 		if(BIO_write(b, s, len) < 0) {
1253 			if(verb) printf("out of memory in BIO_write\n");
1254 			exit(0);
1255 		}
1256 	}
1257 }
1258 
1259 /**
1260  * XML fetch value of particular attribute(by name) or NULL if not present.
1261  * @param atts: attribute array (from xml_startelem).
1262  * @param name: name of attribute to look for.
1263  * @return the value or NULL. (ptr into atts).
1264  */
1265 static const XML_Char*
1266 find_att(const XML_Char **atts, const XML_Char* name)
1267 {
1268 	int i;
1269 	for(i=0; atts[i]; i+=2) {
1270 		if(strcasecmp(atts[i], name) == 0)
1271 			return atts[i+1];
1272 	}
1273 	return NULL;
1274 }
1275 
1276 /**
1277  * XML convert DateTime element to time_t.
1278  * [-]CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
1279  * (with optional .ssssss fractional seconds)
1280  * @param str: the string
1281  * @return a time_t representation or 0 on failure.
1282  */
1283 static time_t
1284 xml_convertdate(const char* str)
1285 {
1286 	time_t t = 0;
1287 	struct tm tm;
1288 	const char* s;
1289 	/* for this application, ignore minus in front;
1290 	 * only positive dates are expected */
1291 	s = str;
1292 	if(s[0] == '-') s++;
1293 	memset(&tm, 0, sizeof(tm));
1294 	/* parse initial content of the string (lots of whitespace allowed) */
1295 	s = strptime(s, "%t%Y%t-%t%m%t-%t%d%tT%t%H%t:%t%M%t:%t%S%t", &tm);
1296 	if(!s) {
1297 		if(verb) printf("xml_convertdate parse failure %s\n", str);
1298 		return 0;
1299 	}
1300 	/* parse remainder of date string */
1301 	if(*s == '.') {
1302 		/* optional '.' and fractional seconds */
1303 		int frac = 0, n = 0;
1304 		if(sscanf(s+1, "%d%n", &frac, &n) < 1) {
1305 			if(verb) printf("xml_convertdate f failure %s\n", str);
1306 			return 0;
1307 		}
1308 		/* fraction is not used, time_t has second accuracy */
1309 		s++;
1310 		s+=n;
1311 	}
1312 	if(*s == 'Z' || *s == 'z') {
1313 		/* nothing to do for this */
1314 		s++;
1315 	} else if(*s == '+' || *s == '-') {
1316 		/* optional timezone spec: Z or +hh:mm or -hh:mm */
1317 		int hr = 0, mn = 0, n = 0;
1318 		if(sscanf(s+1, "%d:%d%n", &hr, &mn, &n) < 2) {
1319 			if(verb) printf("xml_convertdate tz failure %s\n", str);
1320 			return 0;
1321 		}
1322 		if(*s == '+') {
1323 			tm.tm_hour += hr;
1324 			tm.tm_min += mn;
1325 		} else {
1326 			tm.tm_hour -= hr;
1327 			tm.tm_min -= mn;
1328 		}
1329 		s++;
1330 		s += n;
1331 	}
1332 	if(*s != 0) {
1333 		/* not ended properly */
1334 		/* but ignore, (lenient) */
1335 	}
1336 
1337 	t = mktime(&tm);
1338 	if(t == (time_t)-1) {
1339 		if(verb) printf("xml_convertdate mktime failure\n");
1340 		return 0;
1341 	}
1342 	return t;
1343 }
1344 
1345 /**
1346  * XML handle the KeyDigest start tag, check validity periods.
1347  */
1348 static void
1349 handle_keydigest(struct xml_data* data, const XML_Char **atts)
1350 {
1351 	data->use_key = 0;
1352 	if(find_att(atts, "validFrom")) {
1353 		time_t from = xml_convertdate(find_att(atts, "validFrom"));
1354 		if(from == 0) {
1355 			if(verb) printf("error: xml cannot be parsed\n");
1356 			exit(0);
1357 		}
1358 		if(data->date < from)
1359 			return;
1360 	}
1361 	if(find_att(atts, "validUntil")) {
1362 		time_t until = xml_convertdate(find_att(atts, "validUntil"));
1363 		if(until == 0) {
1364 			if(verb) printf("error: xml cannot be parsed\n");
1365 			exit(0);
1366 		}
1367 		if(data->date > until)
1368 			return;
1369 	}
1370 	/* yes we want to use this key */
1371 	data->use_key = 1;
1372 	(void)BIO_reset(data->ctag);
1373 	(void)BIO_reset(data->calgo);
1374 	(void)BIO_reset(data->cdigtype);
1375 	(void)BIO_reset(data->cdigest);
1376 }
1377 
1378 /** See if XML element equals the zone name */
1379 static int
1380 xml_is_zone_name(BIO* zone, const char* name)
1381 {
1382 	char buf[1024];
1383 	char* z = NULL;
1384 	long zlen;
1385 	(void)BIO_seek(zone, 0);
1386 	zlen = BIO_get_mem_data(zone, &z);
1387 	if(!zlen || !z) return 0;
1388 	/* zero terminate */
1389 	if(zlen >= (long)sizeof(buf)) return 0;
1390 	memmove(buf, z, (size_t)zlen);
1391 	buf[zlen] = 0;
1392 	/* compare */
1393 	return (strncasecmp(buf, name, strlen(name)) == 0);
1394 }
1395 
1396 /**
1397  * XML start of element. This callback is called whenever an XML tag starts.
1398  * XML_Char is UTF8.
1399  * @param userData: the xml_data structure.
1400  * @param name: the tag that starts.
1401  * @param atts: array of strings, pairs of attr = value, ends with NULL.
1402  * 	i.e. att[0]="att[1]" att[2]="att[3]" att[4]isNull
1403  */
1404 static void
1405 xml_startelem(void *userData, const XML_Char *name, const XML_Char **atts)
1406 {
1407 	struct xml_data* data = (struct xml_data*)userData;
1408 	BIO* b;
1409 	if(verb>=4) printf("xml tag start '%s'\n", name);
1410 	free(data->tag);
1411 	data->tag = strdup(name);
1412 	if(!data->tag) {
1413 		if(verb) printf("out of memory\n");
1414 		exit(0);
1415 	}
1416 	if(verb>=4) {
1417 		int i;
1418 		for(i=0; atts[i]; i+=2) {
1419 			printf("  %s='%s'\n", atts[i], atts[i+1]);
1420 		}
1421 	}
1422 	/* handle attributes to particular types */
1423 	if(strcasecmp(name, "KeyDigest") == 0) {
1424 		handle_keydigest(data, atts);
1425 		return;
1426 	} else if(strcasecmp(name, "Zone") == 0) {
1427 		(void)BIO_reset(data->czone);
1428 		return;
1429 	}
1430 
1431 	/* for other types we prepare to pick up the data */
1432 	if(!data->use_key)
1433 		return;
1434 	b = xml_selectbio(data, data->tag);
1435 	if(b) {
1436 		/* empty it */
1437 		(void)BIO_reset(b);
1438 	}
1439 }
1440 
1441 /** Append str to bio */
1442 static void
1443 xml_append_str(BIO* b, const char* s)
1444 {
1445 	if(BIO_write(b, s, (int)strlen(s)) < 0) {
1446 		if(verb) printf("out of memory in BIO_write\n");
1447 		exit(0);
1448 	}
1449 }
1450 
1451 /** Append bio to bio */
1452 static void
1453 xml_append_bio(BIO* b, BIO* a)
1454 {
1455 	char* z = NULL;
1456 	long i, len;
1457 	(void)BIO_seek(a, 0);
1458 	len = BIO_get_mem_data(a, &z);
1459 	if(!len || !z) {
1460 		if(verb) printf("out of memory in BIO_write\n");
1461 		exit(0);
1462 	}
1463 	/* remove newlines in the data here */
1464 	for(i=0; i<len; i++) {
1465 		if(z[i] == '\r' || z[i] == '\n')
1466 			z[i] = ' ';
1467 	}
1468 	/* write to BIO */
1469 	if(BIO_write(b, z, len) < 0) {
1470 		if(verb) printf("out of memory in BIO_write\n");
1471 		exit(0);
1472 	}
1473 }
1474 
1475 /** write the parsed xml-DS to the DS list */
1476 static void
1477 xml_append_ds(struct xml_data* data)
1478 {
1479 	/* write DS to accumulated DS */
1480 	xml_append_str(data->ds, ". IN DS ");
1481 	xml_append_bio(data->ds, data->ctag);
1482 	xml_append_str(data->ds, " ");
1483 	xml_append_bio(data->ds, data->calgo);
1484 	xml_append_str(data->ds, " ");
1485 	xml_append_bio(data->ds, data->cdigtype);
1486 	xml_append_str(data->ds, " ");
1487 	xml_append_bio(data->ds, data->cdigest);
1488 	xml_append_str(data->ds, "\n");
1489 	data->num_keys++;
1490 }
1491 
1492 /**
1493  * XML end of element. This callback is called whenever an XML tag ends.
1494  * XML_Char is UTF8.
1495  * @param userData: the xml_data structure
1496  * @param name: the tag that ends.
1497  */
1498 static void
1499 xml_endelem(void *userData, const XML_Char *name)
1500 {
1501 	struct xml_data* data = (struct xml_data*)userData;
1502 	if(verb>=4) printf("xml tag end   '%s'\n", name);
1503 	free(data->tag);
1504 	data->tag = NULL;
1505 	if(strcasecmp(name, "KeyDigest") == 0) {
1506 		if(data->use_key)
1507 			xml_append_ds(data);
1508 		data->use_key = 0;
1509 	} else if(strcasecmp(name, "Zone") == 0) {
1510 		if(!xml_is_zone_name(data->czone, ".")) {
1511 			if(verb) printf("xml not for the right zone\n");
1512 			exit(0);
1513 		}
1514 	}
1515 }
1516 
1517 /* Stop the parser when an entity declaration is encountered. For safety. */
1518 static void
1519 xml_entitydeclhandler(void *userData,
1520 	const XML_Char *ATTR_UNUSED(entityName),
1521 	int ATTR_UNUSED(is_parameter_entity),
1522 	const XML_Char *ATTR_UNUSED(value), int ATTR_UNUSED(value_length),
1523 	const XML_Char *ATTR_UNUSED(base),
1524 	const XML_Char *ATTR_UNUSED(systemId),
1525 	const XML_Char *ATTR_UNUSED(publicId),
1526 	const XML_Char *ATTR_UNUSED(notationName))
1527 {
1528 	(void)XML_StopParser((XML_Parser)userData, XML_FALSE);
1529 }
1530 
1531 /**
1532  * XML parser setup of the callbacks for the tags
1533  */
1534 static void
1535 xml_parse_setup(XML_Parser parser, struct xml_data* data, time_t now)
1536 {
1537 	char buf[1024];
1538 	memset(data, 0, sizeof(*data));
1539 	XML_SetUserData(parser, data);
1540 	data->parser = parser;
1541 	data->date = now;
1542 	data->ds = BIO_new(BIO_s_mem());
1543 	data->ctag = BIO_new(BIO_s_mem());
1544 	data->czone = BIO_new(BIO_s_mem());
1545 	data->calgo = BIO_new(BIO_s_mem());
1546 	data->cdigtype = BIO_new(BIO_s_mem());
1547 	data->cdigest = BIO_new(BIO_s_mem());
1548 	if(!data->ds || !data->ctag || !data->calgo || !data->czone ||
1549 		!data->cdigtype || !data->cdigest) {
1550 		if(verb) printf("out of memory\n");
1551 		exit(0);
1552 	}
1553 	snprintf(buf, sizeof(buf), "; created by unbound-anchor on %s",
1554 		ctime(&now));
1555 	if(BIO_write(data->ds, buf, (int)strlen(buf)) < 0) {
1556 		if(verb) printf("out of memory\n");
1557 		exit(0);
1558 	}
1559 	XML_SetEntityDeclHandler(parser, xml_entitydeclhandler);
1560 	XML_SetElementHandler(parser, xml_startelem, xml_endelem);
1561 	XML_SetCharacterDataHandler(parser, xml_charhandle);
1562 }
1563 
1564 /**
1565  * Perform XML parsing of the root-anchors file
1566  * Its format description can be read here
1567  * https://data.iana.org/root-anchors/draft-icann-dnssec-trust-anchor.txt
1568  * It uses libexpat.
1569  * @param xml: BIO with xml data.
1570  * @param now: the current time for checking DS validity periods.
1571  * @return memoryBIO with the DS data in zone format.
1572  * 	or NULL if the zone is insecure.
1573  * 	(It exit()s on error)
1574  */
1575 static BIO*
1576 xml_parse(BIO* xml, time_t now)
1577 {
1578 	char* pp;
1579 	int len;
1580 	XML_Parser parser;
1581 	struct xml_data data;
1582 
1583 	parser = XML_ParserCreate(NULL);
1584 	if(!parser) {
1585 		if(verb) printf("could not XML_ParserCreate\n");
1586 		exit(0);
1587 	}
1588 
1589 	/* setup callbacks */
1590 	xml_parse_setup(parser, &data, now);
1591 
1592 	/* parse it */
1593 	(void)BIO_reset(xml);
1594 	len = (int)BIO_get_mem_data(xml, &pp);
1595 	if(!len || !pp) {
1596 		if(verb) printf("out of memory\n");
1597 		exit(0);
1598 	}
1599 	if(!XML_Parse(parser, pp, len, 1 /*isfinal*/ )) {
1600 		const char *e = XML_ErrorString(XML_GetErrorCode(parser));
1601 		if(verb) printf("XML_Parse failure %s\n", e?e:"");
1602 		exit(0);
1603 	}
1604 
1605 	/* parsed */
1606 	if(verb) printf("XML was parsed successfully, %d keys\n",
1607 			data.num_keys);
1608 	free(data.tag);
1609 	XML_ParserFree(parser);
1610 
1611 	if(verb >= 4) {
1612 		(void)BIO_seek(data.ds, 0);
1613 		len = BIO_get_mem_data(data.ds, &pp);
1614 		printf("got DS bio %d: '", len);
1615 		if(!fwrite(pp, (size_t)len, 1, stdout))
1616 			/* compilers do not allow us to ignore fwrite .. */
1617 			fprintf(stderr, "error writing to stdout\n");
1618 		printf("'\n");
1619 	}
1620 	BIO_free(data.czone);
1621 	BIO_free(data.ctag);
1622 	BIO_free(data.calgo);
1623 	BIO_free(data.cdigtype);
1624 	BIO_free(data.cdigest);
1625 
1626 	if(data.num_keys == 0) {
1627 		/* the root zone seems to have gone insecure */
1628 		BIO_free(data.ds);
1629 		return NULL;
1630 	} else {
1631 		return data.ds;
1632 	}
1633 }
1634 
1635 /* get key usage out of its extension, returns 0 if no key_usage extension */
1636 static unsigned long
1637 get_usage_of_ex(X509* cert)
1638 {
1639 	unsigned long val = 0;
1640 	ASN1_BIT_STRING* s;
1641 	if((s=X509_get_ext_d2i(cert, NID_key_usage, NULL, NULL))) {
1642 		if(s->length > 0) {
1643 			val = s->data[0];
1644 			if(s->length > 1)
1645 				val |= s->data[1] << 8;
1646 		}
1647 		ASN1_BIT_STRING_free(s);
1648 	}
1649 	return val;
1650 }
1651 
1652 /** get valid signers from the list of signers in the signature */
1653 static STACK_OF(X509)*
1654 get_valid_signers(PKCS7* p7, const char* p7signer)
1655 {
1656 	int i;
1657 	STACK_OF(X509)* validsigners = sk_X509_new_null();
1658 	STACK_OF(X509)* signers = PKCS7_get0_signers(p7, NULL, 0);
1659 	unsigned long usage = 0;
1660 	if(!validsigners) {
1661 		if(verb) printf("out of memory\n");
1662 		sk_X509_free(signers);
1663 		return NULL;
1664 	}
1665 	if(!signers) {
1666 		if(verb) printf("no signers in pkcs7 signature\n");
1667 		sk_X509_free(validsigners);
1668 		return NULL;
1669 	}
1670 	for(i=0; i<sk_X509_num(signers); i++) {
1671 		X509_NAME* nm = X509_get_subject_name(
1672 			sk_X509_value(signers, i));
1673 		char buf[1024];
1674 		if(!nm) {
1675 			if(verb) printf("signer %d: cert has no subject name\n", i);
1676 			continue;
1677 		}
1678 		if(verb && nm) {
1679 			char* nmline = X509_NAME_oneline(nm, buf,
1680 				(int)sizeof(buf));
1681 			printf("signer %d: Subject: %s\n", i,
1682 				nmline?nmline:"no subject");
1683 			if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1684 				NID_commonName, buf, (int)sizeof(buf)))
1685 				printf("commonName: %s\n", buf);
1686 			if(verb >= 3 && X509_NAME_get_text_by_NID(nm,
1687 				NID_pkcs9_emailAddress, buf, (int)sizeof(buf)))
1688 				printf("emailAddress: %s\n", buf);
1689 		}
1690 		if(verb) {
1691 			int ku_loc = X509_get_ext_by_NID(
1692 				sk_X509_value(signers, i), NID_key_usage, -1);
1693 			if(verb >= 3 && ku_loc >= 0) {
1694 				X509_EXTENSION *ex = X509_get_ext(
1695 					sk_X509_value(signers, i), ku_loc);
1696 				if(ex) {
1697 					printf("keyUsage: ");
1698 					X509V3_EXT_print_fp(stdout, ex, 0, 0);
1699 					printf("\n");
1700 				}
1701 			}
1702 		}
1703 		if(!p7signer || strcmp(p7signer, "")==0) {
1704 			/* there is no name to check, return all records */
1705 			if(verb) printf("did not check commonName of signer\n");
1706 		} else {
1707 			if(!X509_NAME_get_text_by_NID(nm,
1708 				NID_pkcs9_emailAddress,
1709 				buf, (int)sizeof(buf))) {
1710 				if(verb) printf("removed cert with no name\n");
1711 				continue; /* no name, no use */
1712 			}
1713 			if(strcmp(buf, p7signer) != 0) {
1714 				if(verb) printf("removed cert with wrong name\n");
1715 				continue; /* wrong name, skip it */
1716 			}
1717 		}
1718 
1719 		/* check that the key usage allows digital signatures
1720 		 * (the p7s) */
1721 		usage = get_usage_of_ex(sk_X509_value(signers, i));
1722 		if(!(usage & KU_DIGITAL_SIGNATURE)) {
1723 			if(verb) printf("removed cert with no key usage Digital Signature allowed\n");
1724 			continue;
1725 		}
1726 
1727 		/* we like this cert, add it to our list of valid
1728 		 * signers certificates */
1729 		sk_X509_push(validsigners, sk_X509_value(signers, i));
1730 	}
1731 	sk_X509_free(signers);
1732 	return validsigners;
1733 }
1734 
1735 /** verify a PKCS7 signature, false on failure */
1736 static int
1737 verify_p7sig(BIO* data, BIO* p7s, STACK_OF(X509)* trust, const char* p7signer)
1738 {
1739 	PKCS7* p7;
1740 	X509_STORE *store = X509_STORE_new();
1741 	STACK_OF(X509)* validsigners;
1742 	int secure = 0;
1743 	int i;
1744 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1745 	X509_VERIFY_PARAM* param = X509_VERIFY_PARAM_new();
1746 	if(!param) {
1747 		if(verb) printf("out of memory\n");
1748 		X509_STORE_free(store);
1749 		return 0;
1750 	}
1751 	/* do the selfcheck on the root certificate; it checks that the
1752 	 * input is valid */
1753 	X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CHECK_SS_SIGNATURE);
1754 	if(store) X509_STORE_set1_param(store, param);
1755 #endif
1756 	if(!store) {
1757 		if(verb) printf("out of memory\n");
1758 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1759 		X509_VERIFY_PARAM_free(param);
1760 #endif
1761 		return 0;
1762 	}
1763 #ifdef X509_V_FLAG_CHECK_SS_SIGNATURE
1764 	X509_VERIFY_PARAM_free(param);
1765 #endif
1766 
1767 	(void)BIO_reset(p7s);
1768 	(void)BIO_reset(data);
1769 
1770 	/* convert p7s to p7 (the signature) */
1771 	p7 = d2i_PKCS7_bio(p7s, NULL);
1772 	if(!p7) {
1773 		if(verb) printf("could not parse p7s signature file\n");
1774 		X509_STORE_free(store);
1775 		return 0;
1776 	}
1777 	if(verb >= 2) printf("parsed the PKCS7 signature\n");
1778 
1779 	/* convert trust to trusted certificate store */
1780 	for(i=0; i<sk_X509_num(trust); i++) {
1781 		if(!X509_STORE_add_cert(store, sk_X509_value(trust, i))) {
1782 			if(verb) printf("failed X509_STORE_add_cert\n");
1783 			X509_STORE_free(store);
1784 			PKCS7_free(p7);
1785 			return 0;
1786 		}
1787 	}
1788 	if(verb >= 2) printf("setup the X509_STORE\n");
1789 
1790 	/* check what is in the Subject name of the certificates,
1791 	 * and build a stack that contains only the right certificates */
1792 	validsigners = get_valid_signers(p7, p7signer);
1793 	if(!validsigners) {
1794 			X509_STORE_free(store);
1795 			PKCS7_free(p7);
1796 			return 0;
1797 	}
1798 	if(PKCS7_verify(p7, validsigners, store, data, NULL, PKCS7_NOINTERN) == 1) {
1799 		secure = 1;
1800 		if(verb) printf("the PKCS7 signature verified\n");
1801 	} else {
1802 		if(verb) {
1803 			ERR_print_errors_fp(stdout);
1804 		}
1805 	}
1806 
1807 	sk_X509_free(validsigners);
1808 	X509_STORE_free(store);
1809 	PKCS7_free(p7);
1810 	return secure;
1811 }
1812 
1813 /** write unsigned root anchor file, a 5011 revoked tp */
1814 static void
1815 write_unsigned_root(const char* root_anchor_file)
1816 {
1817 	FILE* out;
1818 	time_t now = time(NULL);
1819 	out = fopen(root_anchor_file, "w");
1820 	if(!out) {
1821 		if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1822 		return;
1823 	}
1824 	if(fprintf(out, "; autotrust trust anchor file\n"
1825 		";;REVOKED\n"
1826 		";;id: . 1\n"
1827 		"; This file was written by unbound-anchor on %s"
1828 		"; It indicates that the root does not use DNSSEC\n"
1829 		"; to restart DNSSEC overwrite this file with a\n"
1830 		"; valid trustanchor or (empty-it and run unbound-anchor)\n"
1831 		, ctime(&now)) < 0) {
1832 		if(verb) printf("failed to write 'unsigned' to %s\n",
1833 			root_anchor_file);
1834 		if(verb && errno != 0) printf("%s\n", strerror(errno));
1835 	}
1836 	fclose(out);
1837 }
1838 
1839 /** write root anchor file */
1840 static void
1841 write_root_anchor(const char* root_anchor_file, BIO* ds)
1842 {
1843 	char* pp = NULL;
1844 	int len;
1845 	FILE* out;
1846 	(void)BIO_seek(ds, 0);
1847 	len = BIO_get_mem_data(ds, &pp);
1848 	if(!len || !pp) {
1849 		if(verb) printf("out of memory\n");
1850 		return;
1851 	}
1852 	out = fopen(root_anchor_file, "w");
1853 	if(!out) {
1854 		if(verb) printf("%s: %s\n", root_anchor_file, strerror(errno));
1855 		return;
1856 	}
1857 	if(fwrite(pp, (size_t)len, 1, out) != 1) {
1858 		if(verb) printf("failed to write all data to %s\n",
1859 			root_anchor_file);
1860 		if(verb && errno != 0) printf("%s\n", strerror(errno));
1861 	}
1862 	fclose(out);
1863 }
1864 
1865 /** Perform the verification and update of the trustanchor file */
1866 static void
1867 verify_and_update_anchor(const char* root_anchor_file, BIO* xml, BIO* p7s,
1868 	STACK_OF(X509)* cert, const char* p7signer)
1869 {
1870 	BIO* ds;
1871 
1872 	/* verify xml file */
1873 	if(!verify_p7sig(xml, p7s, cert, p7signer)) {
1874 		printf("the PKCS7 signature failed\n");
1875 		exit(0);
1876 	}
1877 
1878 	/* parse the xml file into DS records */
1879 	ds = xml_parse(xml, time(NULL));
1880 	if(!ds) {
1881 		/* the root zone is unsigned now */
1882 		write_unsigned_root(root_anchor_file);
1883 	} else {
1884 		/* reinstate 5011 tracking */
1885 		write_root_anchor(root_anchor_file, ds);
1886 	}
1887 	BIO_free(ds);
1888 }
1889 
1890 #ifdef USE_WINSOCK
1891 static void do_wsa_cleanup(void) { WSACleanup(); }
1892 #endif
1893 
1894 /** perform actual certupdate work */
1895 static int
1896 do_certupdate(const char* root_anchor_file, const char* root_cert_file,
1897 	const char* urlname, const char* xmlname, const char* p7sname,
1898 	const char* p7signer, const char* res_conf, const char* root_hints,
1899 	const char* debugconf, int ip4only, int ip6only, int port,
1900 	struct ub_result* dnskey)
1901 {
1902 	STACK_OF(X509)* cert;
1903 	BIO *xml, *p7s;
1904 	struct ip_list* ip_list = NULL;
1905 
1906 	/* read pem file or provide builtin */
1907 	cert = read_cert_or_builtin(root_cert_file);
1908 
1909 	/* lookup A, AAAA for the urlname (or parse urlname if IP address) */
1910 	ip_list = resolve_name(urlname, port, res_conf, root_hints, debugconf,
1911 		ip4only, ip6only);
1912 
1913 #ifdef USE_WINSOCK
1914 	if(1) { /* libunbound finished, startup WSA for the https connection */
1915 		WSADATA wsa_data;
1916 		int r;
1917 		if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0) {
1918 			if(verb) printf("WSAStartup failed: %s\n",
1919 				wsa_strerror(r));
1920 			exit(0);
1921 		}
1922 		atexit(&do_wsa_cleanup);
1923 	}
1924 #endif
1925 
1926 	/* fetch the necessary files over HTTPS */
1927 	xml = https(ip_list, xmlname, urlname);
1928 	p7s = https(ip_list, p7sname, urlname);
1929 
1930 	/* verify and update the root anchor */
1931 	verify_and_update_anchor(root_anchor_file, xml, p7s, cert, p7signer);
1932 	if(verb) printf("success: the anchor has been updated "
1933 			"using the cert\n");
1934 
1935 	free_file_bio(xml);
1936 	free_file_bio(p7s);
1937 #ifndef S_SPLINT_S
1938 	sk_X509_pop_free(cert, X509_free);
1939 #endif
1940 	ub_resolve_free(dnskey);
1941 	ip_list_free(ip_list);
1942 	return 1;
1943 }
1944 
1945 /**
1946  * Try to read the root RFC5011 autotrust anchor file,
1947  * @param file: filename.
1948  * @return:
1949  * 	0 if does not exist or empty
1950  * 	1 if trust-point-revoked-5011
1951  * 	2 if it is OK.
1952  */
1953 static int
1954 try_read_anchor(const char* file)
1955 {
1956 	int empty = 1;
1957 	char line[10240];
1958 	char* p;
1959 	FILE* in = fopen(file, "r");
1960 	if(!in) {
1961 		/* only if the file does not exist, can we fix it */
1962 		if(errno != ENOENT) {
1963 			if(verb) printf("%s: %s\n", file, strerror(errno));
1964 			if(verb) printf("error: cannot access the file\n");
1965 			exit(0);
1966 		}
1967 		if(verb) printf("%s does not exist\n", file);
1968 		return 0;
1969 	}
1970 	while(fgets(line, (int)sizeof(line), in)) {
1971 		line[sizeof(line)-1] = 0;
1972 		if(strncmp(line, ";;REVOKED", 9) == 0) {
1973 			fclose(in);
1974 			if(verb) printf("%s : the trust point is revoked\n"
1975 				"and the zone is considered unsigned.\n"
1976 				"if you wish to re-enable, delete the file\n",
1977 				file);
1978 			return 1;
1979 		}
1980 		p=line;
1981 		while(*p == ' ' || *p == '\t')
1982 			p++;
1983 		if(p[0]==0 || p[0]=='\n' || p[0]==';') continue;
1984 		/* this line is a line of content */
1985 		empty = 0;
1986 	}
1987 	fclose(in);
1988 	if(empty) {
1989 		if(verb) printf("%s is empty\n", file);
1990 		return 0;
1991 	}
1992 	if(verb) printf("%s has content\n", file);
1993 	return 2;
1994 }
1995 
1996 /** Write the builtin root anchor to a file */
1997 static void
1998 write_builtin_anchor(const char* file)
1999 {
2000 	const char* builtin_root_anchor = get_builtin_ds();
2001 	FILE* out = fopen(file, "w");
2002 	if(!out) {
2003 		if(verb) printf("%s: %s\n", file, strerror(errno));
2004 		if(verb) printf("  could not write builtin anchor\n");
2005 		return;
2006 	}
2007 	if(!fwrite(builtin_root_anchor, strlen(builtin_root_anchor), 1, out)) {
2008 		if(verb) printf("%s: %s\n", file, strerror(errno));
2009 		if(verb) printf("  could not complete write builtin anchor\n");
2010 	}
2011 	fclose(out);
2012 }
2013 
2014 /**
2015  * Check the root anchor file.
2016  * If does not exist, provide builtin and write file.
2017  * If empty, provide builtin and write file.
2018  * If trust-point-revoked-5011 file: make the program exit.
2019  * @param root_anchor_file: filename of the root anchor.
2020  * @param used_builtin: set to 1 if the builtin is written.
2021  * @return 0 if trustpoint is insecure, 1 on success.  Exit on failure.
2022  */
2023 static int
2024 provide_builtin(const char* root_anchor_file, int* used_builtin)
2025 {
2026 	/* try to read it */
2027 	switch(try_read_anchor(root_anchor_file))
2028 	{
2029 		case 0: /* no exist or empty */
2030 			write_builtin_anchor(root_anchor_file);
2031 			*used_builtin = 1;
2032 			break;
2033 		case 1: /* revoked tp */
2034 			return 0;
2035 		case 2: /* it is fine */
2036 		default:
2037 			break;
2038 	}
2039 	return 1;
2040 }
2041 
2042 /**
2043  * add an autotrust anchor for the root to the context
2044  */
2045 static void
2046 add_5011_probe_root(struct ub_ctx* ctx, const char* root_anchor_file)
2047 {
2048 	int r;
2049 	r = ub_ctx_set_option(ctx, "auto-trust-anchor-file:", root_anchor_file);
2050 	if(r) {
2051 		if(verb) printf("add 5011 probe to ctx: %s\n", ub_strerror(r));
2052 		ub_ctx_delete(ctx);
2053 		exit(0);
2054 	}
2055 }
2056 
2057 /**
2058  * Prime the root key and return the result.  Exit on error.
2059  * @param ctx: the unbound context to perform the priming with.
2060  * @return: the result of the prime, on error it exit()s.
2061  */
2062 static struct ub_result*
2063 prime_root_key(struct ub_ctx* ctx)
2064 {
2065 	struct ub_result* res = NULL;
2066 	int r;
2067 	r = ub_resolve(ctx, ".", LDNS_RR_TYPE_DNSKEY, LDNS_RR_CLASS_IN, &res);
2068 	if(r) {
2069 		if(verb) printf("resolve DNSKEY: %s\n", ub_strerror(r));
2070 		ub_ctx_delete(ctx);
2071 		exit(0);
2072 	}
2073 	if(!res) {
2074 		if(verb) printf("out of memory\n");
2075 		ub_ctx_delete(ctx);
2076 		exit(0);
2077 	}
2078 	return res;
2079 }
2080 
2081 /** see if ADDPEND keys exist in autotrust file (if possible) */
2082 static int
2083 read_if_pending_keys(const char* file)
2084 {
2085 	FILE* in = fopen(file, "r");
2086 	char line[8192];
2087 	if(!in) {
2088 		if(verb>=2) printf("%s: %s\n", file, strerror(errno));
2089 		return 0;
2090 	}
2091 	while(fgets(line, (int)sizeof(line), in)) {
2092 		if(line[0]==';') continue;
2093 		if(strstr(line, "[ ADDPEND ]")) {
2094 			fclose(in);
2095 			if(verb) printf("RFC5011-state has ADDPEND keys\n");
2096 			return 1;
2097 		}
2098 	}
2099 	fclose(in);
2100 	return 0;
2101 }
2102 
2103 /** read last successful probe time from autotrust file (if possible) */
2104 static int32_t
2105 read_last_success_time(const char* file)
2106 {
2107 	FILE* in = fopen(file, "r");
2108 	char line[1024];
2109 	if(!in) {
2110 		if(verb) printf("%s: %s\n", file, strerror(errno));
2111 		return 0;
2112 	}
2113 	while(fgets(line, (int)sizeof(line), in)) {
2114 		if(strncmp(line, ";;last_success: ", 16) == 0) {
2115 			char* e;
2116 			time_t x = (unsigned int)strtol(line+16, &e, 10);
2117 			fclose(in);
2118 			if(line+16 == e) {
2119 				if(verb) printf("failed to parse "
2120 					"last_success probe time\n");
2121 				return 0;
2122 			}
2123 			if(verb) printf("last successful probe: %s", ctime(&x));
2124 			return (int32_t)x;
2125 		}
2126 	}
2127 	fclose(in);
2128 	if(verb) printf("no last_success probe time in anchor file\n");
2129 	return 0;
2130 }
2131 
2132 /**
2133  * Read autotrust 5011 probe file and see if the date
2134  * compared to the current date allows a certupdate.
2135  * If the last successful probe was recent then 5011 cannot be behind,
2136  * and the failure cannot be solved with a certupdate.
2137  * The debugconf is to validation-override the date for testing.
2138  * @param root_anchor_file: filename of root key
2139  * @return true if certupdate is ok.
2140  */
2141 static int
2142 probe_date_allows_certupdate(const char* root_anchor_file)
2143 {
2144 	int has_pending_keys = read_if_pending_keys(root_anchor_file);
2145 	int32_t last_success = read_last_success_time(root_anchor_file);
2146 	int32_t now = (int32_t)time(NULL);
2147 	int32_t leeway = 30 * 24 * 3600; /* 30 days leeway */
2148 	/* if the date is before 2010-07-15:00.00.00 then the root has not
2149 	 * been signed yet, and thus we refuse to take action. */
2150 	if(time(NULL) < xml_convertdate("2010-07-15T00:00:00")) {
2151 		if(verb) printf("the date is before the root was first signed,"
2152 			" please correct the clock\n");
2153 		return 0;
2154 	}
2155 	if(last_success == 0)
2156 		return 1; /* no probe time */
2157 	if(has_pending_keys)
2158 		return 1; /* key in ADDPEND state, a previous probe has
2159 		inserted that, and it was present in all recent probes,
2160 		but it has not become active.  The 30 day timer may not have
2161 		expired, but we know(for sure) there is a rollover going on.
2162 		If we only managed to pickup the new key on its last day
2163 		of announcement (for example) this can happen. */
2164 	if(now - last_success < 0) {
2165 		if(verb) printf("the last successful probe is in the future,"
2166 			" clock was modified\n");
2167 		return 0;
2168 	}
2169 	if(now - last_success >= leeway) {
2170 		if(verb) printf("the last successful probe was more than 30 "
2171 			"days ago\n");
2172 		return 1;
2173 	}
2174 	if(verb) printf("the last successful probe is recent\n");
2175 	return 0;
2176 }
2177 
2178 /** perform the unbound-anchor work */
2179 static int
2180 do_root_update_work(const char* root_anchor_file, const char* root_cert_file,
2181 	const char* urlname, const char* xmlname, const char* p7sname,
2182 	const char* p7signer, const char* res_conf, const char* root_hints,
2183 	const char* debugconf, int ip4only, int ip6only, int force, int port)
2184 {
2185 	struct ub_ctx* ctx;
2186 	struct ub_result* dnskey;
2187 	int used_builtin = 0;
2188 
2189 	/* see if builtin rootanchor needs to be provided, or if
2190 	 * rootanchor is 'revoked-trust-point' */
2191 	if(!provide_builtin(root_anchor_file, &used_builtin))
2192 		return 0;
2193 
2194 	/* make unbound context with 5011-probe for root anchor,
2195 	 * and probe . DNSKEY */
2196 	ctx = create_unbound_context(res_conf, root_hints, debugconf,
2197 		ip4only, ip6only);
2198 	add_5011_probe_root(ctx, root_anchor_file);
2199 	dnskey = prime_root_key(ctx);
2200 	ub_ctx_delete(ctx);
2201 
2202 	/* if secure: exit */
2203 	if(dnskey->secure && !force) {
2204 		if(verb) printf("success: the anchor is ok\n");
2205 		ub_resolve_free(dnskey);
2206 		return used_builtin;
2207 	}
2208 	if(force && verb) printf("debug cert update forced\n");
2209 
2210 	/* if not (and NOERROR): check date and do certupdate */
2211 	if((dnskey->rcode == 0 &&
2212 		probe_date_allows_certupdate(root_anchor_file)) || force) {
2213 		if(do_certupdate(root_anchor_file, root_cert_file, urlname,
2214 			xmlname, p7sname, p7signer, res_conf, root_hints,
2215 			debugconf, ip4only, ip6only, port, dnskey))
2216 			return 1;
2217 		return used_builtin;
2218 	}
2219 	if(verb) printf("fail: the anchor is NOT ok and could not be fixed\n");
2220 	ub_resolve_free(dnskey);
2221 	return used_builtin;
2222 }
2223 
2224 /** getopt global, in case header files fail to declare it. */
2225 extern int optind;
2226 /** getopt global, in case header files fail to declare it. */
2227 extern char* optarg;
2228 
2229 /** Main routine for unbound-anchor */
2230 int main(int argc, char* argv[])
2231 {
2232 	int c;
2233 	const char* root_anchor_file = ROOT_ANCHOR_FILE;
2234 	const char* root_cert_file = ROOT_CERT_FILE;
2235 	const char* urlname = URLNAME;
2236 	const char* xmlname = XMLNAME;
2237 	const char* p7sname = P7SNAME;
2238 	const char* p7signer = P7SIGNER;
2239 	const char* res_conf = NULL;
2240 	const char* root_hints = NULL;
2241 	const char* debugconf = NULL;
2242 	int dolist=0, ip4only=0, ip6only=0, force=0, port = HTTPS_PORT;
2243 	/* parse the options */
2244 	while( (c=getopt(argc, argv, "46C:FP:a:c:f:hln:r:s:u:vx:")) != -1) {
2245 		switch(c) {
2246 		case 'l':
2247 			dolist = 1;
2248 			break;
2249 		case '4':
2250 			ip4only = 1;
2251 			break;
2252 		case '6':
2253 			ip6only = 1;
2254 			break;
2255 		case 'a':
2256 			root_anchor_file = optarg;
2257 			break;
2258 		case 'c':
2259 			root_cert_file = optarg;
2260 			break;
2261 		case 'u':
2262 			urlname = optarg;
2263 			break;
2264 		case 'x':
2265 			xmlname = optarg;
2266 			break;
2267 		case 's':
2268 			p7sname = optarg;
2269 			break;
2270 		case 'n':
2271 			p7signer = optarg;
2272 			break;
2273 		case 'f':
2274 			res_conf = optarg;
2275 			break;
2276 		case 'r':
2277 			root_hints = optarg;
2278 			break;
2279 		case 'C':
2280 			debugconf = optarg;
2281 			break;
2282 		case 'F':
2283 			force = 1;
2284 			break;
2285 		case 'P':
2286 			port = atoi(optarg);
2287 			break;
2288 		case 'v':
2289 			verb++;
2290 			break;
2291 		case '?':
2292 		case 'h':
2293 		default:
2294 			usage();
2295 		}
2296 	}
2297 	argc -= optind;
2298 	argv += optind;
2299 	if(argc != 0)
2300 		usage();
2301 
2302 	ERR_load_crypto_strings();
2303 	ERR_load_SSL_strings();
2304 	OpenSSL_add_all_algorithms();
2305 	(void)SSL_library_init();
2306 
2307 	if(dolist) do_list_builtin();
2308 
2309 	return do_root_update_work(root_anchor_file, root_cert_file, urlname,
2310 		xmlname, p7sname, p7signer, res_conf, root_hints, debugconf,
2311 		ip4only, ip6only, force, port);
2312 }
2313