1 /* $NetBSD: ecs.c,v 1.7 2025/01/26 16:25:22 christos Exp $ */ 2 3 /* 4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC") 5 * 6 * SPDX-License-Identifier: MPL-2.0 7 * 8 * This Source Code Form is subject to the terms of the Mozilla Public 9 * License, v. 2.0. If a copy of the MPL was not distributed with this 10 * file, you can obtain one at https://mozilla.org/MPL/2.0/. 11 * 12 * See the COPYRIGHT file distributed with this work for additional 13 * information regarding copyright ownership. 14 */ 15 16 /*! \file */ 17 18 #include <string.h> 19 20 #include <isc/buffer.h> 21 #include <isc/mem.h> 22 #include <isc/netaddr.h> 23 #include <isc/util.h> 24 25 #include <dns/ecs.h> 26 #include <dns/nsec.h> 27 #include <dns/rbt.h> 28 #include <dns/rdata.h> 29 #include <dns/rdatatype.h> 30 #include <dns/result.h> 31 #include <dns/types.h> 32 33 void 34 dns_ecs_init(dns_ecs_t *ecs) { 35 isc_netaddr_unspec(&ecs->addr); 36 ecs->source = 0; 37 ecs->scope = 0xff; 38 } 39 40 bool 41 dns_ecs_equals(const dns_ecs_t *ecs1, const dns_ecs_t *ecs2) { 42 const unsigned char *addr1, *addr2; 43 uint8_t mask; 44 size_t alen; 45 46 REQUIRE(ecs1 != NULL && ecs2 != NULL); 47 48 if (ecs1->source != ecs2->source || 49 ecs1->addr.family != ecs2->addr.family) 50 { 51 return false; 52 } 53 54 alen = (ecs1->source + 7) / 8; 55 if (alen == 0) { 56 return true; 57 } 58 59 switch (ecs1->addr.family) { 60 case AF_INET: 61 INSIST(alen <= 4); 62 addr1 = (const unsigned char *)&ecs1->addr.type.in; 63 addr2 = (const unsigned char *)&ecs2->addr.type.in; 64 break; 65 case AF_INET6: 66 INSIST(alen <= 16); 67 addr1 = (const unsigned char *)&ecs1->addr.type.in6; 68 addr2 = (const unsigned char *)&ecs2->addr.type.in6; 69 break; 70 default: 71 UNREACHABLE(); 72 } 73 74 /* 75 * Compare all octets except the final octet of the address 76 * prefix. 77 */ 78 if (alen > 1 && memcmp(addr1, addr2, alen - 1) != 0) { 79 return false; 80 } 81 82 /* 83 * It should not be necessary to mask the final octet; all 84 * bits past the source prefix length are supposed to be 0. 85 * However, it seems prudent not to omit them from the 86 * comparison anyway. 87 */ 88 mask = (~0U << (8 - (ecs1->source % 8))) & 0xff; 89 if (mask == 0) { 90 mask = 0xff; 91 } 92 93 if ((addr1[alen - 1] & mask) != (addr2[alen - 1] & mask)) { 94 return false; 95 } 96 97 return true; 98 } 99 100 void 101 dns_ecs_format(const dns_ecs_t *ecs, char *buf, size_t size) { 102 size_t len; 103 char *p; 104 105 REQUIRE(ecs != NULL); 106 REQUIRE(buf != NULL); 107 REQUIRE(size >= DNS_ECS_FORMATSIZE); 108 109 isc_netaddr_format(&ecs->addr, buf, size); 110 len = strlen(buf); 111 p = buf + len; 112 snprintf(p, size - len, "/%d/%d", ecs->source, 113 ecs->scope == 0xff ? 0 : ecs->scope); 114 } 115