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