utils.c 27.6 KB
Newer Older
1
/*  Copyright (C) 2014-2017 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
2 3 4 5 6 7 8 9 10 11 12 13

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
14
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
15 16
 */

17
#include "lib/utils.h"
18

19 20 21
#include "contrib/ccan/asprintf/asprintf.h"
#include "contrib/cleanup.h"
#include "contrib/ucw/mempool.h"
22
#include "kresconfig.h"
23
#include "lib/defines.h"
24
#include "lib/generic/array.h"
25
#include "lib/module.h"
26
#include "lib/nsrep.h"
27
#include "lib/resolve.h"
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include <gnutls/gnutls.h>
#include <libknot/descriptor.h>
#include <libknot/dname.h>
#include <libknot/rrset-dump.h>
#include <libknot/rrtype/rrsig.h>
#include <libknot/version.h>
#include <uv.h>

#include <arpa/inet.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/un.h>
44 45

/* Always compile-in log symbols, even if disabled. */
46
#undef kr_verbose_status
47 48
#undef kr_verbose_set
#undef kr_log_verbose
49

50
/* Logging & debugging */
51
bool kr_verbose_status = false;
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
void *mm_realloc(knot_mm_t *mm, void *what, size_t size, size_t prev_size)
{
	if (mm) {
		void *p = mm->alloc(mm->ctx, size);
		if (p == NULL) {
			return NULL;
		} else {
			if (what) {
				memcpy(p, what,
				       prev_size < size ? prev_size : size);
			}
			mm_free(mm, what);
			return p;
		}
	} else {
		return realloc(what, size);
	}
}
71 72 73 74 75 76

void *mm_malloc(void *ctx, size_t n)
{
	(void)ctx;
	return malloc(n);
}
77 78 79 80 81 82 83 84 85 86 87 88
void *mm_malloc_aligned(void *ctx, size_t n)
{
	size_t alignment = (size_t)ctx;
	void *res;
	int err = posix_memalign(&res, alignment, n);
	if (err == 0) {
		return res;
	} else {
		assert(err == -1 && errno == ENOMEM);
		return NULL;
	}
}
89

90 91 92 93 94
/*
 * Macros.
 */
#define strlen_safe(x) ((x) ? strlen(x) : 0)

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
/**
 * @internal Convert 16bit unsigned to string, keeps leading spaces.
 * @note Always fills dst length = 5
 * Credit: http://computer-programming-forum.com/46-asm/7aa4b50bce8dd985.htm
 */
static inline int u16tostr(uint8_t *dst, uint16_t num)
{
	uint32_t tmp = num * (((1 << 28) / 10000) + 1) - (num / 4);
	for(size_t i = 0; i < 5; i++) {
		dst[i] = '0' + (char) (tmp >> 28);
		tmp = (tmp & 0x0fffffff) * 10;
	}
	return 5;
}

110 111 112
/*
 * Cleanup callbacks.
 */
113

114 115
static void kres_gnutls_log(int level, const char *message)
{
116
	kr_log_verbose("[gnutls] (%d) %s", level, message);
117 118
}

119
bool kr_verbose_set(bool status)
120
{
121
#ifndef NOVERBOSELOG
122
	kr_verbose_status = status;
123 124 125 126 127 128 129

	/* gnutls logs messages related to our TLS and also libdnssec,
	 * and the logging is set up in a global way only */
	if (status) {
		gnutls_global_set_log_function(kres_gnutls_log);
	}
	gnutls_global_set_log_level(status ? 5 : 0);
130
#endif
131
	return kr_verbose_status;
132 133
}

134
void kr_log_verbose(const char *fmt, ...)
135
{
136
	if (unlikely(kr_verbose_status)) {
137 138 139 140 141
		va_list args;
		va_start(args, fmt);
		vprintf(fmt, args);
		va_end(args);
	}
142 143
}

144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
void kr_log_qverbose_impl(const struct kr_query *qry, const char *cls, const char *fmt, ...)
{
	unsigned ind = 0;
	for (const struct kr_query *q = qry; q; q = q->parent)
		ind += 2;
	uint32_t qry_uid = qry ? qry->uid : 0;
	uint32_t req_uid = qry && qry->request ? qry->request->uid : 0;
	/* Simplified kr_log_verbose() calls, first prefix then passed fmt...
	 * Calling it would take about the same amount of code. */
	printf("[%05u.%02u][%s] %*s", req_uid, qry_uid, cls, ind, "");
	va_list args;
	va_start(args, fmt);
	vprintf(fmt, args);
	va_end(args);
}

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
bool kr_log_trace(const struct kr_query *query, const char *source, const char *fmt, ...)
{
	if (!kr_log_trace_enabled(query)) {
		return false;
	}

	auto_free char *msg = NULL;

	va_list args;
	va_start(args, fmt);
	int len = vasprintf(&msg, fmt, args);
	va_end(args);

	/* Check formatting result before logging */
	if (len < 0) {
		return false;
	}

	query->request->trace_log(query, source, msg);
	return true;
}

182 183
char* kr_strcatdup(unsigned n, ...)
{
184 185 186 187
	if (n < 1) {
		return NULL;
	}

188 189 190 191 192 193
	/* Calculate total length */
	size_t total_len = 0;
	va_list vl;
	va_start(vl, n);
	for (unsigned i = 0; i < n; ++i) {
		char *item = va_arg(vl, char *);
194
		const size_t new_len = total_len + strlen_safe(item);
195 196 197 198
		if (unlikely(new_len < total_len)) {
			va_end(vl);
			return NULL;
		}
199
		total_len = new_len;
200 201 202 203 204 205
	}
	va_end(vl);

	/* Allocate result and fill */
	char *result = NULL;
	if (total_len > 0) {
206
		if (unlikely(total_len + 1 == 0)) return NULL;
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
		result = malloc(total_len + 1);
	}
	if (result) {
		char *stream = result;
		va_start(vl, n);
		for (unsigned i = 0; i < n; ++i) {
			char *item = va_arg(vl, char *);
			if (item) {
				size_t len = strlen(item);
				memcpy(stream, item, len + 1);
				stream += len;
			}
		}
		va_end(vl);
	}

	return result;
}
225

226
int kr_memreserve(void *baton, char **mem, size_t elm_size, size_t want, size_t *have)
227 228 229 230
{
    if (*have >= want) {
        return 0;
    } else {
231
        knot_mm_t *pool = baton;
232 233 234
        size_t next_size = array_next_count(want);
        void *mem_new = mm_alloc(pool, next_size * elm_size);
        if (mem_new != NULL) {
235 236 237 238
	    if (*mem) { /* 0-length memcpy from NULL isn't technically OK */
		memcpy(mem_new, *mem, (*have)*(elm_size));
		mm_free(pool, *mem);
	    }
239 240 241 242 243 244 245
            *mem = mem_new;
            *have = next_size;
            return 0;
        }
    }
    return -1;
}
246

247
static int pkt_recycle(knot_pkt_t *pkt, bool keep_question)
248
{
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
	/* The maximum size of a header + query name + (class, type) */
	uint8_t buf[KNOT_WIRE_HEADER_SIZE + KNOT_DNAME_MAXLEN + 2 * sizeof(uint16_t)];

	/* Save header and the question section */
	size_t base_size = KNOT_WIRE_HEADER_SIZE;
	if (keep_question) {
		base_size += knot_pkt_question_size(pkt);
	}
	assert(base_size <= sizeof(buf));
	memcpy(buf, pkt->wire, base_size);

	/* Clear the packet and its auxiliary structures */
	knot_pkt_clear(pkt);

	/* Restore header and question section and clear counters */
	pkt->size = base_size;
	memcpy(pkt->wire, buf, base_size);
	knot_wire_set_qdcount(pkt->wire, keep_question);
267 268 269
	knot_wire_set_ancount(pkt->wire, 0);
	knot_wire_set_nscount(pkt->wire, 0);
	knot_wire_set_arcount(pkt->wire, 0);
270 271

	/* Reparse question */
272 273 274 275
	knot_pkt_begin(pkt, KNOT_ANSWER);
	return knot_pkt_parse_question(pkt);
}

276 277 278 279 280
int kr_pkt_recycle(knot_pkt_t *pkt)
{
	return pkt_recycle(pkt, false);
}

281 282
int kr_pkt_clear_payload(knot_pkt_t *pkt)
{
283
	return pkt_recycle(pkt, knot_wire_get_qdcount(pkt->wire));
284 285
}

286 287 288
int kr_pkt_put(knot_pkt_t *pkt, const knot_dname_t *name, uint32_t ttl,
               uint16_t rclass, uint16_t rtype, const uint8_t *rdata, uint16_t rdlen)
{
289 290
	/* LATER(opt.): there's relatively lots of copying, but ATM kr_pkt_put()
	 * isn't considered to be used in any performance-critical parts (just lua). */
291 292 293 294 295
	if (!pkt || !name)  {
		return kr_error(EINVAL);
	}
	/* Create empty RR */
	knot_rrset_t rr;
296
	knot_rrset_init(&rr, knot_dname_copy(name, &pkt->mm), rtype, rclass, ttl);
297
	/* Create RDATA */
298
	knot_rdata_t *rdata_tmp = mm_alloc(&pkt->mm, offsetof(knot_rdata_t, data) + rdlen);
299 300
	knot_rdata_init(rdata_tmp, rdlen, rdata);
	knot_rdataset_add(&rr.rrs, rdata_tmp, &pkt->mm);
301
	mm_free(&pkt->mm, rdata_tmp); /* we're always on mempool for now, but whatever */
302 303 304
	/* Append RR */
	return knot_pkt_put(pkt, 0, &rr, KNOT_PF_FREE);
}
305

306 307 308 309 310 311 312
void kr_pkt_make_auth_header(knot_pkt_t *pkt)
{
	assert(pkt && pkt->wire);
	knot_wire_clear_ad(pkt->wire);
	knot_wire_set_aa(pkt->wire);
}

313 314 315 316 317 318 319 320 321 322 323 324
const char *kr_inaddr(const struct sockaddr *addr)
{
	if (!addr) {
		return NULL;
	}
	switch (addr->sa_family) {
	case AF_INET:  return (const char *)&(((const struct sockaddr_in *)addr)->sin_addr);
	case AF_INET6: return (const char *)&(((const struct sockaddr_in6 *)addr)->sin6_addr);
	default:       return NULL;
	}
}

325 326 327 328 329 330 331
int kr_inaddr_family(const struct sockaddr *addr)
{
	if (!addr)
		return AF_UNSPEC;
	return addr->sa_family;
}

332 333 334 335 336
int kr_inaddr_len(const struct sockaddr *addr)
{
	if (!addr) {
		return kr_error(EINVAL);
	}
337
	return kr_family_len(addr->sa_family);
338 339
}

340 341 342 343 344 345 346 347
int kr_sockaddr_len(const struct sockaddr *addr)
{
	if (!addr) {
		return kr_error(EINVAL);
	}
	switch (addr->sa_family) {
	case AF_INET:  return sizeof(struct sockaddr_in);
	case AF_INET6: return sizeof(struct sockaddr_in6);
348
	case AF_UNIX:  return sizeof(struct sockaddr_un);
349 350 351 352
	default:       return kr_error(EINVAL);
	}
}

353 354 355 356 357 358 359 360 361 362 363 364 365 366
int kr_sockaddr_cmp(const struct sockaddr *left, const struct sockaddr *right)
{
	if (!left || !right) {
		return kr_error(EINVAL);
	}
	if (left->sa_family != right->sa_family) {
		return kr_error(EFAULT);
	}
	if (left->sa_family == AF_INET) {
		struct sockaddr_in *left_in = (struct sockaddr_in *)left;
		struct sockaddr_in *right_in = (struct sockaddr_in *)right;
		if (left_in->sin_addr.s_addr != right_in->sin_addr.s_addr) {
			return kr_error(EFAULT);
		}
367 368 369
		if (left_in->sin_port != right_in->sin_port) {
			return kr_error(EFAULT);
		}
370 371 372 373 374 375 376
	} else if (left->sa_family == AF_INET6) {
		struct sockaddr_in6 *left_in6 = (struct sockaddr_in6 *)left;
		struct sockaddr_in6 *right_in6 = (struct sockaddr_in6 *)right;
		if (memcmp(&left_in6->sin6_addr, &right_in6->sin6_addr,
			   sizeof(struct in6_addr)) != 0) {
			return kr_error(EFAULT);
		}
377 378 379
		if (left_in6->sin6_port != right_in6->sin6_port) {
			return kr_error(EFAULT);
		}
380 381 382 383 384 385
	} else {
		return kr_error(ENOENT);
	}
	return kr_ok();
}

386 387 388 389 390 391 392 393 394 395 396 397
uint16_t kr_inaddr_port(const struct sockaddr *addr)
{
	if (!addr) {
		return 0;
	}
	switch (addr->sa_family) {
	case AF_INET:  return ntohs(((const struct sockaddr_in *)addr)->sin_port);
	case AF_INET6: return ntohs(((const struct sockaddr_in6 *)addr)->sin6_port);
	default:       return 0;
	}
}

398 399 400 401 402 403 404 405 406 407 408 409
void kr_inaddr_set_port(struct sockaddr *addr, uint16_t port)
{
	if (!addr) {
		return;
	}
	switch (addr->sa_family) {
	case AF_INET:  ((struct sockaddr_in *)addr)->sin_port = htons(port);
	case AF_INET6: ((struct sockaddr_in6 *)addr)->sin6_port = htons(port);
	default: break;
	}
}

410 411
int kr_inaddr_str(const struct sockaddr *addr, char *buf, size_t *buflen)
{
412 413 414 415 416 417 418 419 420 421
	if (!addr) {
		return kr_error(EINVAL);
	}
	return kr_ntop_str(addr->sa_family, kr_inaddr(addr), kr_inaddr_port(addr),
			   buf, buflen);
}

int kr_ntop_str(int family, const void *src, uint16_t port, char *buf, size_t *buflen)
{
	if (!src || !buf || !buflen) {
422 423 424
		return kr_error(EINVAL);
	}

425
	if (!inet_ntop(family, src, buf, *buflen)) {
426 427
		return kr_error(errno);
	}
428 429 430 431 432
	const int len = strlen(buf);
	const int len_need = len + 1 + 5 + 1;
	if (len_need > *buflen) {
		*buflen = len_need;
		return kr_error(ENOSPC);
433
	}
434 435
	*buflen = len_need;
	buf[len] = '#';
436
	u16tostr((uint8_t *)&buf[len + 1], port);
437 438
	buf[len_need - 1] = 0;
	return kr_ok();
439 440
}

441
int kr_straddr_family(const char *addr)
442 443 444 445
{
	if (!addr) {
		return kr_error(EINVAL);
	}
446 447 448
	if (addr[0] == '/') {
		return AF_UNIX;
	}
449 450 451 452
	if (strchr(addr, ':')) {
		return AF_INET6;
	}
	return AF_INET;
453 454
}

455 456
int kr_family_len(int family)
{
457 458 459 460 461
	switch (family) {
	case AF_INET:  return sizeof(struct in_addr);
	case AF_INET6: return sizeof(struct in6_addr);
	default:       return kr_error(EINVAL);
	}
462 463
}

464
struct sockaddr * kr_straddr_socket(const char *addr, int port, knot_mm_t *pool)
465 466 467
{
	switch (kr_straddr_family(addr)) {
	case AF_INET: {
468
		struct sockaddr_in *res = mm_alloc(pool, sizeof(*res));
469 470 471
		if (uv_ip4_addr(addr, port, res) >= 0) {
			return (struct sockaddr *)res;
		} else {
472
			mm_free(pool, res);
473 474 475 476
			return NULL;
		}
	}
	case AF_INET6: {
477
		struct sockaddr_in6 *res = mm_alloc(pool, sizeof(*res));
478 479 480
		if (uv_ip6_addr(addr, port, res) >= 0) {
			return (struct sockaddr *)res;
		} else {
481
			mm_free(pool, res);
482 483 484
			return NULL;
		}
	}
485 486 487 488 489 490 491 492 493 494 495
	case AF_UNIX: {
		struct sockaddr_un *res;
		const size_t alen = strlen(addr) + 1;
		if (alen > sizeof(res->sun_path)) {
			return NULL;
		}
		res = mm_alloc(pool, sizeof(*res));
		res->sun_family = AF_UNIX;
		memcpy(res->sun_path, addr, alen);
		return (struct sockaddr *)res;
	}
496
	default:
497
		assert(!EINVAL);
498 499 500 501
		return NULL;
	}
}

502 503 504 505 506 507 508 509 510 511 512 513 514
int kr_straddr_subnet(void *dst, const char *addr)
{
	if (!dst || !addr) {
		return kr_error(EINVAL);
	}
	/* Parse subnet */
	int bit_len = 0;
	int family = kr_straddr_family(addr);
	auto_free char *addr_str = strdup(addr);
	char *subnet = strchr(addr_str, '/');
	if (subnet) {
		*subnet = '\0';
		subnet += 1;
515
		bit_len = strtol(subnet, NULL, 10);
516 517 518 519 520
		/* Check client subnet length */
		const int max_len = (family == AF_INET6) ? 128 : 32;
		if (bit_len < 0 || bit_len > max_len) {
			return kr_error(ERANGE);
		}
521 522 523
	} else {
		/* No subnet, use maximal subnet length. */
		bit_len = (family == AF_INET6) ? 128 : 32;
524 525 526 527 528 529 530 531 532 533
	}
	/* Parse address */
	int ret = inet_pton(family, addr_str, dst);
	if (ret < 0) {
		return kr_error(EILSEQ);
	}

	return bit_len;
}

534 535
int kr_straddr_split(const char *instr, char ipaddr[static restrict (INET6_ADDRSTRLEN + 1)],
		     uint16_t *port)
536
{
537
	assert(instr && ipaddr && port);
538
	/* Find where port number starts. */
539
	const char *p_start = strchr(instr, '@');
540
	if (!p_start)
541 542 543 544 545 546 547 548 549 550 551 552
		p_start = strchr(instr, '#');
	if (p_start) { /* Get and check the port number. */
		if (p_start[1] == '\0') /* Don't accept empty port string. */
			return kr_error(EILSEQ);
		char *p_end;
		long p = strtol(p_start + 1, &p_end, 10);
		if (*p_end != '\0' || p <= 0 || p > UINT16_MAX)
			return kr_error(EILSEQ);
		*port = p;
	}
	/* Copy the address. */
	const size_t addrlen = p_start ? p_start - instr : strlen(instr);
553
	if (addrlen > INET6_ADDRSTRLEN)
554 555 556 557
		return kr_error(EILSEQ);
	memcpy(ipaddr, instr, addrlen);
	ipaddr[addrlen] = '\0';
	return kr_ok();
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
}

int kr_straddr_join(const char *addr, uint16_t port, char *buf, size_t *buflen)
{
	if (!addr || !buf || !buflen) {
		return kr_error(EINVAL);
	}

	struct sockaddr_storage ss;
	int family = kr_straddr_family(addr);
	if (family == kr_error(EINVAL) || !inet_pton(family, addr, &ss)) {
		return kr_error(EINVAL);
	}

	int len = strlen(addr);
	if (len + 6 >= *buflen) {
		return kr_error(ENOSPC);
	}

	memcpy(buf, addr, len + 1);
	buf[len] = '#';
	u16tostr((uint8_t *)&buf[len + 1], port);
	len += 6;
	buf[len] = 0;
	*buflen = len;

	return kr_ok();
}

587 588
int kr_bitcmp(const char *a, const char *b, int bits)
{
589 590 591 592 593 594 595 596 597 598
	/* We're using the function from lua directly, so at least for now
	 * we avoid crashing on bogus inputs.  Meaning: NULL is ordered before
	 * anything else, and negative length is the same as zero.
	 * TODO: review the call sites and probably remove the checks. */
	if (bits <= 0 || (!a && !b)) {
		return 0;
	} else if (!a) {
		return -1;
	} else if (!b) {
		return 1;
599
	}
600

601
	assert((a && b && bits >= 0)  ||  bits == 0);
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
	/* Compare part byte-divisible part. */
	const size_t chunk = bits / 8;
	int ret = memcmp(a, b, chunk);
	if (ret != 0) {
		return ret;
	}
	a += chunk;
	b += chunk;
	bits -= chunk * 8;
	/* Compare last partial byte address block. */
	if (bits > 0) {
		const size_t shift = (8 - bits);
		ret = ((uint8_t)(*a >> shift) - (uint8_t)(*b >> shift));
	}
	return ret;
617 618
}

619 620
int kr_rrkey(char *key, uint16_t class, const knot_dname_t *owner,
	     uint16_t type, uint16_t additional)
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
{
	if (!key || !owner) {
		return kr_error(EINVAL);
	}
	uint8_t *key_buf = (uint8_t *)key;
	int ret = u16tostr(key_buf, class);
	if (ret <= 0) {
		return ret;
	}
	key_buf += ret;
	ret = knot_dname_to_wire(key_buf, owner, KNOT_DNAME_MAXLEN);
	if (ret <= 0) {
		return ret;
	}
	knot_dname_to_lower(key_buf);
	key_buf += ret - 1;
	ret = u16tostr(key_buf, type);
	if (ret <= 0) {
		return ret;
	}
	key_buf += ret;
	ret = u16tostr(key_buf, additional);
	if (ret <= 0) {
		return ret;
	}
	key_buf[ret] = '\0';
	return (char *)&key_buf[ret] - key;
}

650 651 652 653 654
/** Return whether two RRsets match, i.e. would form the same set; see ranked_rr_array_t */
static inline bool rrsets_match(const knot_rrset_t *rr1, const knot_rrset_t *rr2)
{
	bool match = rr1->type == rr2->type && rr1->rclass == rr2->rclass;
	if (match && rr2->type == KNOT_RRTYPE_RRSIG) {
655 656
		match = match && knot_rrsig_type_covered(rr1->rrs.rdata)
				  == knot_rrsig_type_covered(rr2->rrs.rdata);
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
	}
	match = match && knot_dname_is_equal(rr1->owner, rr2->owner);
	return match;
}

/** Ensure that an index in a ranked array won't cause "duplicate" RRsets on wire.
 *
 * Other entries that would form the same RRset get to_wire = false.
 * See also rrsets_match.
 */
static int to_wire_ensure_unique(ranked_rr_array_t *array, size_t index)
{
	bool ok = array && index < array->len;
	if (!ok) {
		assert(false);
		return kr_error(EINVAL);
	}

	const struct ranked_rr_array_entry *e0 = array->at[index];
	if (!e0->to_wire) {
		return kr_ok();
	}

	for (ssize_t i = array->len - 1; i >= 0; --i) {
		/* ^ iterate backwards, as the end is more likely in CPU caches */
		struct ranked_rr_array_entry *ei = array->at[i];
		if (ei->qry_uid == e0->qry_uid /* assumption: no duplicates within qry */
		    || !ei->to_wire /* no use for complex comparison if @to_wire */
		   ) {
			continue;
		}
		if (rrsets_match(ei->rr, e0->rr)) {
			ei->to_wire = false;
		}
	}
	return kr_ok();
}

695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
int kr_ranked_rrarray_add(ranked_rr_array_t *array, const knot_rrset_t *rr,
			  uint8_t rank, bool to_wire, uint32_t qry_uid, knot_mm_t *pool)
{
	/* rr always has one record per rrset
	 * check if another rrset with the same
	 * rclass/type/owner combination exists within current query
	 * and merge if needed */
	for (ssize_t i = array->len - 1; i >= 0; --i) {
		ranked_rr_array_entry_t *stashed = array->at[i];
		if (stashed->yielded) {
			break;
		}
		if (stashed->qry_uid != qry_uid) {
			break;
		}
710 711 712 713
		if (!rrsets_match(stashed->rr, rr)) {
			continue;
		}
		/* Found the entry to merge with.  Check consistency and merge. */
714
		bool ok = stashed->rank == rank && !stashed->cached;
715 716 717
		if (!ok) {
			assert(false);
			return kr_error(EEXIST);
718
		}
719 720 721 722 723
		/* It may happen that an RRset is first considered useful
		 * (to_wire = false, e.g. due to being part of glue),
		 * and later we may find we also want it in the answer. */
		stashed->to_wire = stashed->to_wire || to_wire;

724
		return knot_rdataset_merge(&stashed->rr->rrs, &rr->rrs, pool);
725 726 727 728 729 730 731 732 733 734 735 736 737 738
	}

	/* No stashed rrset found, add */
	int ret = array_reserve_mm(*array, array->len + 1, kr_memreserve, pool);
	if (ret != 0) {
		return kr_error(ENOMEM);
	}

	ranked_rr_array_entry_t *entry = mm_alloc(pool, sizeof(ranked_rr_array_entry_t));
	if (!entry) {
		return kr_error(ENOMEM);
	}
	knot_rrset_t *copy = knot_rrset_copy(rr, pool);
	if (!copy) {
739
		mm_free(pool, entry);
740 741 742 743 744 745
		return kr_error(ENOMEM);
	}

	entry->qry_uid = qry_uid;
	entry->rr = copy;
	entry->rank = rank;
746
	entry->revalidation_cnt = 0;
747 748 749
	entry->cached = false;
	entry->yielded = false;
	entry->to_wire = to_wire;
750 751 752 753 754 755
	if (array_push(*array, entry) < 0) {
		/* Silence coverity.  It shouldn't be possible to happen,
		 * due to the array_reserve_mm call above. */
		mm_free(pool, entry);
		return kr_error(ENOMEM);
	}
756 757

	return to_wire_ensure_unique(array, array->len - 1);
758 759
}

760
int kr_ranked_rrarray_set_wire(ranked_rr_array_t *array, bool to_wire,
761 762
			       uint32_t qry_uid, bool check_dups,
			       bool (*extraCheck)(const ranked_rr_array_entry_t *))
763 764 765
{
	for (size_t i = 0; i < array->len; ++i) {
		ranked_rr_array_entry_t *entry = array->at[i];
766 767 768
		if (entry->qry_uid != qry_uid) {
			continue;
		}
769 770 771
		if (extraCheck != NULL && !extraCheck(entry)) {
			continue;
		}
772
		entry->to_wire = to_wire;
773 774 775
		if (check_dups) {
			int ret = to_wire_ensure_unique(array, i);
			if (ret) return ret;
776 777 778 779 780 781
		}
	}
	return kr_ok();
}


782 783
static char *callprop(struct kr_module *module, const char *prop, const char *input, void *env)
{
784
	if (!module || !module->props || !prop) {
785 786
		return NULL;
	}
787
	for (const struct kr_prop *p = module->props; p && p->name; ++p) {
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
		if (p->cb != NULL && strcmp(p->name, prop) == 0) {
			return p->cb(env, module, input);
		}
	}
	return NULL;
}

char *kr_module_call(struct kr_context *ctx, const char *module, const char *prop, const char *input)
{
	if (!ctx || !ctx->modules || !module || !prop) {
		return NULL;
	}
	module_array_t *mod_list = ctx->modules;
	for (size_t i = 0; i < mod_list->len; ++i) {
		struct kr_module *mod = mod_list->at[i];
		if (strcmp(mod->name, module) == 0) {
			return callprop(mod, prop, input, ctx);
		}
	}
	return NULL;
808
}
809

810 811 812 813 814 815 816 817
static void flags_to_str(char *dst, const knot_pkt_t *pkt, size_t maxlen)
{
	int offset = 0;
	int ret = 0;
	struct {
		uint8_t (*get) (const uint8_t *packet);
		char name[3];
	} flag[7] = {
818 819 820 821 822
		{knot_wire_get_qr, "qr"},
		{knot_wire_get_aa, "aa"},
		{knot_wire_get_rd, "rd"},
		{knot_wire_get_ra, "ra"},
		{knot_wire_get_tc, "tc"},
823 824
		{knot_wire_get_ad, "ad"},
		{knot_wire_get_cd, "cd"}
825 826 827 828 829 830 831 832 833 834 835
	};
	for (int i = 0; i < 7; ++i) {
		if (!flag[i].get(pkt->wire)) {
			continue;
		}
		ret = snprintf(dst + offset, maxlen, "%s ", flag[i].name);
		if (ret <= 0 || ret >= maxlen) {
			dst[0] = 0;
			return;
		}
		offset += ret;
836
		maxlen -= ret;
837 838 839 840
	}
	dst[offset] = 0;
}

841
static char *print_section_opt(struct mempool *mp, char *endp, const knot_rrset_t *rr, const uint8_t rcode)
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
{
	uint8_t ercode = knot_edns_get_ext_rcode(rr);
	uint16_t ext_rcode_id = knot_edns_whole_rcode(ercode, rcode);
	const char *ext_rcode_str = "Unused";
	const knot_lookup_t *ext_rcode;

	if (ercode > 0) {
		ext_rcode = knot_lookup_by_id(knot_rcode_names, ext_rcode_id);
		if (ext_rcode != NULL) {
			ext_rcode_str = ext_rcode->name;
		} else {
			ext_rcode_str = "Unknown";
		}
	}

857 858 859 860 861 862 863
	return mp_printf_append(mp, endp,
		";; EDNS PSEUDOSECTION:\n;; "
		"Version: %u; flags: %s; UDP size: %u B; ext-rcode: %s\n\n",
		knot_edns_get_version(rr),
		(knot_edns_do(rr) != 0) ? "do" : "",
		knot_edns_get_payload(rr),
		ext_rcode_str);
864 865 866

}

867
char *kr_pkt_text(const knot_pkt_t *pkt)
868
{
869 870 871 872 873 874
	if (!pkt) {
		return NULL;
	}

	struct mempool *mp = mp_new(512);

875 876 877
	static const char * snames[] = {
		";; ANSWER SECTION", ";; AUTHORITY SECTION", ";; ADDITIONAL SECTION"
	};
878
	char flags[32];
879
	uint8_t pkt_rcode = knot_wire_get_rcode(pkt->wire);
880 881 882 883 884 885
	uint8_t pkt_opcode = knot_wire_get_opcode(pkt->wire);
	const char *rcode_str = "Unknown";
	const char *opcode_str = "Unknown";
	const knot_lookup_t *rcode = knot_lookup_by_id(knot_rcode_names, pkt_rcode);
	const knot_lookup_t *opcode = knot_lookup_by_id(knot_opcode_names, pkt_opcode);
	uint16_t qry_id = knot_wire_get_id(pkt->wire);
886
	uint16_t qdcount = knot_wire_get_qdcount(pkt->wire);
887 888 889 890 891 892 893

	if (rcode != NULL) {
		rcode_str = rcode->name;
	}
	if (opcode != NULL) {
		opcode_str = opcode->name;
	}
894
	flags_to_str(flags, pkt, sizeof(flags));
895

896 897 898 899 900 901 902 903 904 905
	char *ptr = mp_printf(mp,
		";; ->>HEADER<<- opcode: %s; status: %s; id: %hu\n"
		";; Flags: %s QUERY: %hu; ANSWER: %hu; "
		"AUTHORITY: %hu; ADDITIONAL: %hu\n\n",
		opcode_str, rcode_str, qry_id,
		flags,
		qdcount,
		knot_wire_get_ancount(pkt->wire),
		knot_wire_get_nscount(pkt->wire),
		knot_wire_get_arcount(pkt->wire));
906 907

	if (knot_pkt_has_edns(pkt)) {
908
		ptr = print_section_opt(mp, ptr, pkt->opt_rr, knot_wire_get_rcode(pkt->wire));
909 910
	}

911
	if (qdcount == 1) {
912 913
		KR_DNAME_GET_STR(qname, knot_pkt_qname(pkt));
		KR_RRTYPE_GET_STR(rrtype, knot_pkt_qtype(pkt));
914
		ptr = mp_printf_append(mp, ptr, ";; QUESTION SECTION\n%s\t\t%s\n", qname, rrtype);
915
	} else if (qdcount > 1) {
916
		ptr = mp_printf_append(mp, ptr, ";; Warning: unsupported QDCOUNT %hu\n", qdcount);
917
	}
918 919

	for (knot_section_t i = KNOT_ANSWER; i <= KNOT_ADDITIONAL; ++i) {
920
		const knot_pktsection_t *sec = knot_pkt_section(pkt, i);
921
		if (sec->count == 0 || knot_pkt_rr(sec, 0)->type == KNOT_RRTYPE_OPT) {
922
			/* OPT RRs are _supposed_ to be the last ^^, if they appear */
923 924
			continue;
		}
925 926

		ptr = mp_printf_append(mp, ptr, "\n%s\n", snames[i - KNOT_ANSWER]);
927 928
		for (unsigned k = 0; k < sec->count; ++k) {
			const knot_rrset_t *rr = knot_pkt_rr(sec, k);
929 930 931 932 933
			if (rr->type == KNOT_RRTYPE_OPT) {
				continue;
			}
			auto_free char *rr_text = kr_rrset_text(rr);
			ptr = mp_printf_append(mp, ptr, "%s", rr_text);
934 935
		}
	}
936

937 938 939 940
	/* Close growing buffer and duplicate result before deleting */
	char *result = strdup(ptr);
	mp_delete(mp);
	return result;
941 942
}

943
char *kr_rrset_text(const knot_rrset_t *rr)
944
{
945 946 947
	if (!rr) {
		return NULL;
	}
948

949
	/* Note: knot_rrset_txt_dump will double the size until the rrset fits */
950 951
	size_t bufsize = 128;
	char *buf = malloc(bufsize);
952 953 954 955 956 957 958
	int ret = knot_rrset_txt_dump(rr, &buf, &bufsize, &KNOT_DUMP_STYLE_DEFAULT);
	if (ret < 0) {
		free(buf);
		return NULL;
	}

	return buf;
959
}
960

Vitezslav Kriz's avatar
Vitezslav Kriz committed
961 962 963 964 965
uint64_t kr_now()
{
	return uv_now(uv_default_loop());
}

966 967 968 969 970
void kr_uv_free_cb(uv_handle_t* handle)
{
	free(handle->data);
}

971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
const char *kr_strptime_diff(const char *format, const char *time1_str,
		             const char *time0_str, double *diff) {
	assert(format != NULL);
	assert(time1_str != NULL);
	assert(time0_str != NULL);
	assert(diff != NULL);

	struct tm time1_tm;
	time_t time1_u;
	struct tm time0_tm;
	time_t time0_u;

	char *err = strptime(time1_str, format, &time1_tm);
	if (err == NULL || err != time1_str + strlen(time1_str))
		return "strptime failed for time1";
	time1_tm.tm_isdst = -1; /* determine if DST is active or not */
	time1_u = mktime(&time1_tm);
	if (time1_u == (time_t)-1)
		return "mktime failed for time1";

	err = strptime(time0_str, format, &time0_tm);
	if (err == NULL || err != time0_str + strlen(time0_str))
		return "strptime failed for time0";
	time0_tm.tm_isdst = -1; /* determine if DST is active or not */
	time0_u = mktime(&time0_tm);
	if (time0_u == (time_t)-1)
		return "mktime failed for time0";
	*diff = difftime(time1_u, time0_u);

	return NULL;
}

1003
int knot_dname_lf2wire(knot_dname_t * const dst, uint8_t len, const uint8_t *lf)
Vladimír Čunát's avatar
.  
Vladimír Čunát committed
1004
{
1005 1006
	knot_dname_t *d = dst; /* moving "cursor" as we write it out */
	bool ok = d && (len == 0 || lf);
Vladimír Čunát's avatar
.  
Vladimír Čunát committed
1007 1008 1009 1010
	if (!ok) {
		assert(false);
		return kr_error(EINVAL);
	}
1011 1012 1013 1014 1015
	/* we allow the final zero byte to be omitted */
	if (!len) {
		goto finish;
	}
	if (lf[len - 1]) {
Vladimír Čunát's avatar
.  
Vladimír Čunát committed
1016
		++len;
1017 1018 1019
	}
	/* convert the name, one label at a time */
	int label_end = len - 1; /* index of the zero byte after the current label */
Vladimír Čunát's avatar
.  
Vladimír Čunát committed
1020 1021
	while (label_end >= 0) {
		/* find label_start */
1022
		int i = label_end - 1;
Vladimír Čunát's avatar
.  
Vladimír Čunát committed
1023 1024
		while (i >= 0 && lf[i])
			--i;
1025 1026 1027 1028
		const int label_start = i + 1; /* index of the first byte of the current label */
		const int label_len = label_end - label_start;
		assert(label_len >= 0);
		if (label_len > 63 || label_len <= 0)
Vladimír Čunát's avatar
.  
Vladimír Čunát committed
1029 1030
			return kr_error(EILSEQ);
		/* write the label */
1031 1032 1033 1034
		*d = label_len;
		++d;
		memcpy(d, lf + label_start, label_len);
		d += label_len;
Vladimír Čunát's avatar
.  
Vladimír Čunát committed
1035
		/* next label */
1036
		label_end = label_start - 1;
Vladimír Čunát's avatar
.  
Vladimír Čunát committed
1037
	}
1038
finish:
1039 1040 1041
	*d = 0; /* the final zero */
	++d;
	return d - dst;
1042
}
1043

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
static void rnd_noerror(void *data, uint size)
{
	int ret = gnutls_rnd(GNUTLS_RND_NONCE, data, size);
	if (ret) {
		kr_log_error("gnutls_rnd(): %s\n", gnutls_strerror(ret));
		abort();
	}
}
void kr_rnd_buffered(void *data, uint size)
{
	/* static circular buffer, from index _begin (inclusive) to _end (exclusive) */
	static uint8_t buf[512/8]; /* gnutls_rnd() works on blocks of 512 bits (chacha) */
	static uint buf_begin = sizeof(buf);

	if (unlikely(size > sizeof(buf))) {
		rnd_noerror(data, size);
		return;
	}
	/* Start with contiguous chunk, possibly until the end of buffer. */
	const uint size1 = MIN(size, sizeof(buf) - buf_begin);
	uint8_t *d = data;
	memcpy(d, buf + buf_begin, size1);
	if (size1 == size) {
		buf_begin += size1;
		return;
	}
	d += size1;
	size -= size1;
	/* Refill the whole buffer, and finish by another contiguous chunk. */
	rnd_noerror(buf, sizeof(buf));
	memcpy(d, buf, size);
	buf_begin = size;
}

1078 1079 1080 1081 1082 1083
void kr_rrset_init(knot_rrset_t *rrset, knot_dname_t *owner,
			uint16_t type, uint16_t rclass, uint32_t ttl)
{
	assert(rrset);
	knot_rrset_init(rrset, owner, type, rclass, ttl);
}
1084 1085 1086 1087
uint16_t kr_pkt_has_dnssec(const knot_pkt_t *pkt)
{
	return knot_pkt_has_dnssec(pkt);
}
1088 1089 1090 1091 1092 1093 1094 1095
uint16_t kr_pkt_qclass(const knot_pkt_t *pkt)
{
	return knot_pkt_qclass(pkt);
}
uint16_t kr_pkt_qtype(const knot_pkt_t *pkt)
{
	return knot_pkt_qtype(pkt);
}
1096
uint32_t kr_rrsig_sig_inception(const knot_rdata_t *rdata)
1097
{
1098
	return knot_rrsig_sig_inception(rdata);
1099
}
1100
uint32_t kr_rrsig_sig_expiration(const knot_rdata_t *rdata)
1101
{
1102
	return knot_rrsig_sig_expiration(rdata);
1103
}
1104 1105 1106 1107
uint16_t kr_rrsig_type_covered(const knot_rdata_t *rdata)
{
	return knot_rrsig_type_covered(rdata);
}
1108