HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/shared/dns-packet.c

106,506 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: c27254297516167354363db6d609d0673060f634

Lines 2001–3000 of 3,202

                return -EBADMSG;
 
        offset = p->rindex;
 
        switch (rr->key->type) {
 
        case DNS_TYPE_SRV:
                r = dns_packet_read_uint16(p, &rr->srv.priority, NULL);
                if (r < 0)
                        return r;
                r = dns_packet_read_uint16(p, &rr->srv.weight, NULL);
                if (r < 0)
                        return r;
                r = dns_packet_read_uint16(p, &rr->srv.port, NULL);
                if (r < 0)
                        return r;
 
                /* RFC 2782 states "Unless and until permitted by future standards action, name compression
                 * is not to be used for this field." Nonetheless, we support it here, in the interest of
                 * increasing compatibility with implementations that do not implement this correctly. After
                 * all we didn't do this right once upon a time ourselves (see
                 * https://github.com/systemd/systemd/issues/9793). */
                r = dns_packet_read_name(p, &rr->srv.name, /* allow_compression= */ true, NULL);
                break;
 
        case DNS_TYPE_PTR:
        case DNS_TYPE_NS:
        case DNS_TYPE_CNAME:
        case DNS_TYPE_DNAME:
                r = dns_packet_read_name(p, &rr->ptr.name, true, NULL);
                break;
 
        case DNS_TYPE_HINFO:
                r = dns_packet_read_string(p, &rr->hinfo.cpu, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_string(p, &rr->hinfo.os, NULL);
                break;
 
        case DNS_TYPE_SPF: /* exactly the same as TXT */
        case DNS_TYPE_TXT:
                if (rdlength <= 0) {
                        r = dns_txt_item_new_empty(&rr->txt.items);
                        if (r < 0)
                                return r;
                } else {
                        DnsTxtItem *last = NULL;
 
                        while (p->rindex - offset < rdlength) {
                                DnsTxtItem *i;
                                const void *data;
                                size_t sz;
 
                                r = dns_packet_read_raw_string(p, &data, &sz, NULL);
                                if (r < 0)
                                        return r;
 
                                i = malloc0(offsetof(DnsTxtItem, data) + sz + 1); /* extra NUL byte at the end */
                                if (!i)
                                        return -ENOMEM;
 
                                memcpy(i->data, data, sz);
                                i->length = sz;
 
                                LIST_INSERT_AFTER(items, rr->txt.items, last, i);
                                last = i;
                        }
                }
 
                r = 0;
                break;
 
        case DNS_TYPE_A:
                r = dns_packet_read_blob(p, &rr->a.in_addr, sizeof(struct in_addr), NULL);
                break;
 
        case DNS_TYPE_AAAA:
                r = dns_packet_read_blob(p, &rr->aaaa.in6_addr, sizeof(struct in6_addr), NULL);
                break;
 
        case DNS_TYPE_SOA:
                r = dns_packet_read_name(p, &rr->soa.mname, true, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_name(p, &rr->soa.rname, true, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint32(p, &rr->soa.serial, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint32(p, &rr->soa.refresh, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint32(p, &rr->soa.retry, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint32(p, &rr->soa.expire, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint32(p, &rr->soa.minimum, NULL);
                break;
 
        case DNS_TYPE_MX:
                r = dns_packet_read_uint16(p, &rr->mx.priority, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_name(p, &rr->mx.exchange, true, NULL);
                break;
 
        case DNS_TYPE_LOC: {
                uint8_t t;
                size_t pos;
 
                r = dns_packet_read_uint8(p, &t, &pos);
                if (r < 0)
                        return r;
 
                if (t == 0) {
                        rr->loc.version = t;
 
                        r = dns_packet_read_uint8(p, &rr->loc.size, NULL);
                        if (r < 0)
                                return r;
 
                        if (!loc_size_ok(rr->loc.size))
                                return -EBADMSG;
 
                        r = dns_packet_read_uint8(p, &rr->loc.horiz_pre, NULL);
                        if (r < 0)
                                return r;
 
                        if (!loc_size_ok(rr->loc.horiz_pre))
                                return -EBADMSG;
 
                        r = dns_packet_read_uint8(p, &rr->loc.vert_pre, NULL);
                        if (r < 0)
                                return r;
 
                        if (!loc_size_ok(rr->loc.vert_pre))
                                return -EBADMSG;
 
                        r = dns_packet_read_uint32(p, &rr->loc.latitude, NULL);
                        if (r < 0)
                                return r;
 
                        r = dns_packet_read_uint32(p, &rr->loc.longitude, NULL);
                        if (r < 0)
                                return r;
 
                        r = dns_packet_read_uint32(p, &rr->loc.altitude, NULL);
                        if (r < 0)
                                return r;
 
                        break;
                } else {
                        dns_packet_rewind(p, pos);
                        rr->unparsable = true;
                        goto unparsable;
                }
        }
 
        case DNS_TYPE_DS:
                r = dns_packet_read_uint16(p, &rr->ds.key_tag, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &rr->ds.algorithm, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &rr->ds.digest_type, NULL);
                if (r < 0)
                        return r;
 
                if (rdlength < 4)
                        return -EBADMSG;
 
                r = dns_packet_read_memdup(p, rdlength - 4,
                                           &rr->ds.digest, &rr->ds.digest_size,
                                           NULL);
                if (r < 0)
                        return r;
 
                if (rr->ds.digest_size <= 0)
                        /* the accepted size depends on the algorithm, but for now
                           just ensure that the value is greater than zero */
                        return -EBADMSG;
 
                break;
 
        case DNS_TYPE_SSHFP:
                r = dns_packet_read_uint8(p, &rr->sshfp.algorithm, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &rr->sshfp.fptype, NULL);
                if (r < 0)
                        return r;
 
                if (rdlength < 2)
                        return -EBADMSG;
 
                r = dns_packet_read_memdup(p, rdlength - 2,
                                           &rr->sshfp.fingerprint, &rr->sshfp.fingerprint_size,
                                           NULL);
 
                if (rr->sshfp.fingerprint_size <= 0)
                        /* the accepted size depends on the algorithm, but for now
                           just ensure that the value is greater than zero */
                        return -EBADMSG;
 
                break;
 
        case DNS_TYPE_DNSKEY:
                r = dns_packet_read_uint16(p, &rr->dnskey.flags, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &rr->dnskey.protocol, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &rr->dnskey.algorithm, NULL);
                if (r < 0)
                        return r;
 
                if (rdlength < 4)
                        return -EBADMSG;
 
                r = dns_packet_read_memdup(p, rdlength - 4,
                                           &rr->dnskey.key, &rr->dnskey.key_size,
                                           NULL);
 
                if (rr->dnskey.key_size <= 0)
                        /* the accepted size depends on the algorithm, but for now
                           just ensure that the value is greater than zero */
                        return -EBADMSG;
 
                break;
 
        case DNS_TYPE_RRSIG:
                r = dns_packet_read_uint16(p, &rr->rrsig.type_covered, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &rr->rrsig.algorithm, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &rr->rrsig.labels, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint32(p, &rr->rrsig.original_ttl, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint32(p, &rr->rrsig.expiration, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint32(p, &rr->rrsig.inception, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint16(p, &rr->rrsig.key_tag, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_name(p, &rr->rrsig.signer, false, NULL);
                if (r < 0)
                        return r;
 
                if (rdlength < p->rindex - offset)
                        return -EBADMSG;
 
                r = dns_packet_read_memdup(p, offset + rdlength - p->rindex,
                                           &rr->rrsig.signature, &rr->rrsig.signature_size,
                                           NULL);
 
                if (rr->rrsig.signature_size <= 0)
                        /* the accepted size depends on the algorithm, but for now
                           just ensure that the value is greater than zero */
                        return -EBADMSG;
 
                break;
 
        case DNS_TYPE_NSEC: {
 
                /*
                 * RFC6762, section 18.14 explicitly states mDNS should use name compression.
                 * This contradicts RFC3845, section 2.1.1
                 */
 
                bool allow_compressed = p->protocol == DNS_PROTOCOL_MDNS;
 
                r = dns_packet_read_name(p, &rr->nsec.next_domain_name, allow_compressed, NULL);
                if (r < 0)
                        return r;
 
                if (rdlength < p->rindex - offset)
                        return -EBADMSG;
 
                r = dns_packet_read_type_windows(p, &rr->nsec.types, offset + rdlength - p->rindex, NULL);
 
                /* We accept empty NSEC bitmaps. The bit indicating the presence of the NSEC record itself
                 * is redundant and in e.g., RFC4956 this fact is used to define a use for NSEC records
                 * without the NSEC bit set. */
 
                break;
        }
        case DNS_TYPE_NSEC3: {
                uint8_t size;
 
                r = dns_packet_read_uint8(p, &rr->nsec3.algorithm, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &rr->nsec3.flags, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint16(p, &rr->nsec3.iterations, NULL);
                if (r < 0)
                        return r;
 
                /* this may be zero */
                r = dns_packet_read_uint8(p, &size, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_memdup(p, size, &rr->nsec3.salt, &rr->nsec3.salt_size, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &size, NULL);
                if (r < 0)
                        return r;
 
                if (size <= 0)
                        return -EBADMSG;
 
                r = dns_packet_read_memdup(p, size,
                                           &rr->nsec3.next_hashed_name, &rr->nsec3.next_hashed_name_size,
                                           NULL);
                if (r < 0)
                        return r;
 
                if (rdlength < p->rindex - offset)
                        return -EBADMSG;
 
                r = dns_packet_read_type_windows(p, &rr->nsec3.types, offset + rdlength - p->rindex, NULL);
 
                /* empty non-terminals can have NSEC3 records, so empty bitmaps are allowed */
 
                break;
        }
 
        case DNS_TYPE_TLSA:
                r = dns_packet_read_uint8(p, &rr->tlsa.cert_usage, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &rr->tlsa.selector, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint8(p, &rr->tlsa.matching_type, NULL);
                if (r < 0)
                        return r;
 
                if (rdlength < 3)
                        return -EBADMSG;
 
                r = dns_packet_read_memdup(p, rdlength - 3,
                                           &rr->tlsa.data, &rr->tlsa.data_size,
                                           NULL);
 
                if (rr->tlsa.data_size <= 0)
                        /* the accepted size depends on the algorithm, but for now
                           just ensure that the value is greater than zero */
                        return -EBADMSG;
 
                break;
 
        case DNS_TYPE_SVCB:
        case DNS_TYPE_HTTPS:
                r = dns_packet_read_uint16(p, &rr->svcb.priority, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_name(p, &rr->svcb.target_name, false /* uncompressed */, NULL);
                if (r < 0)
                        return r;
 
                DnsSvcParam *last = NULL;
                while (p->rindex - offset < rdlength) {
                        _cleanup_free_ DnsSvcParam *i = NULL;
                        uint16_t svc_param_key;
                        uint16_t sz;
 
                        r = dns_packet_read_uint16(p, &svc_param_key, NULL);
                        if (r < 0)
                                return r;
                        /* RFC 9460, section 2.2 says we must consider an RR malformed if SvcParamKeys are
                         * not in strictly increasing order */
                        if (last && last->key >= svc_param_key)
                                return -EBADMSG;
 
                        r = dns_packet_read_uint16(p, &sz, NULL);
                        if (r < 0)
                                return r;
 
                        i = malloc0(offsetof(DnsSvcParam, value) + sz);
                        if (!i)
                                return -ENOMEM;
 
                        i->key = svc_param_key;
                        i->length = sz;
                        r = dns_packet_read_blob(p, &i->value, sz, NULL);
                        if (r < 0)
                                return r;
                        if (!dns_svc_param_is_valid(i))
                                return -EBADMSG;
 
                        LIST_INSERT_AFTER(params, rr->svcb.params, last, i);
                        last = TAKE_PTR(i);
                }
 
                break;
 
        case DNS_TYPE_CAA:
                r = dns_packet_read_uint8(p, &rr->caa.flags, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_string(p, &rr->caa.tag, NULL);
                if (r < 0)
                        return r;
 
                if (rdlength < p->rindex - offset)
                        return -EBADMSG;
 
                r = dns_packet_read_memdup(p,
                                           rdlength + offset - p->rindex,
                                           &rr->caa.value, &rr->caa.value_size, NULL);
 
                break;
 
        case DNS_TYPE_NAPTR:
                r = dns_packet_read_uint16(p, &rr->naptr.order, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_uint16(p, &rr->naptr.preference, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_string(p, &rr->naptr.flags, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_string(p, &rr->naptr.services, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_string(p, &rr->naptr.regexp, NULL);
                if (r < 0)
                        return r;
 
                r = dns_packet_read_name(p, &rr->naptr.replacement, /* allow_compression= */ false, NULL);
                break;
 
        case DNS_TYPE_OPT: /* we only care about the header of OPT for now. */
        case DNS_TYPE_OPENPGPKEY:
        default:
        unparsable:
                r = dns_packet_read_memdup(p, rdlength, &rr->generic.data, &rr->generic.data_size, NULL);
        }
        if (r < 0)
                return r;
        if (p->rindex - offset != rdlength)
                return -EBADMSG;
 
        if (ret)
                *ret = TAKE_PTR(rr);
        if (ret_cache_flush)
                *ret_cache_flush = cache_flush;
        if (ret_start)
                *ret_start = rewinder.saved_rindex;
 
        CANCEL_REWINDER(rewinder);
        return 0;
}
 
static bool opt_is_good(DnsResourceRecord *rr, bool *rfc6975) {
        const uint8_t* p;
        bool found_dau_dhu_n3u = false;
        size_t l;
 
        /* Checks whether the specified OPT RR is well-formed and whether it contains RFC6975 data (which is not OK in
         * a reply). */
 
        assert(rr);
        assert(rfc6975);
        assert(rr->key->type == DNS_TYPE_OPT);
 
        /* Check that the version is 0 */
        if (((rr->ttl >> 16) & UINT32_C(0xFF)) != 0) {
                *rfc6975 = false;
                return true; /* if it's not version 0, it's OK, but we will ignore the OPT field contents */
        }
 
        p = rr->opt.data;
        l = rr->opt.data_size;
        while (l > 0) {
                uint16_t option_code, option_length;
 
                /* At least four bytes for OPTION-CODE and OPTION-LENGTH are required */
                if (l < 4U)
                        return false;
 
                option_code = unaligned_read_be16(p);
                option_length = unaligned_read_be16(p + 2);
 
                if (l < option_length + 4U)
                        return false;
 
                /* RFC 6975 DAU, DHU or N3U fields found. */
                if (IN_SET(option_code, DNS_EDNS_OPT_DAU, DNS_EDNS_OPT_DHU, DNS_EDNS_OPT_N3U))
                        found_dau_dhu_n3u = true;
 
                p += option_length + 4U;
                l -= option_length + 4U;
        }
 
        *rfc6975 = found_dau_dhu_n3u;
        return true;
}
 
static int dns_packet_extract_question(DnsPacket *p, DnsQuestion **ret_question) {
        _cleanup_(dns_question_unrefp) DnsQuestion *question = NULL;
        unsigned n, prealloc;
        int r;
 
        assert(ret_question);
 
        n = DNS_PACKET_QDCOUNT(p);
        if (n == 0) {
                *ret_question = NULL;
                return 0;
        }
 
        /* Calculate the maximum number of potential questions the remaining packet data can actually
         * contain: p->size - p->rindex are the remaining unread bytes in the packet, and 5U is the minimum
         * size of each question - 1 (QNAME) + 2 (QTYPE) + 2 (QCLASS). */
        prealloc = (p->size - p->rindex) / 5U;
        if (prealloc == 0)
                /* QDCOUNT > 0 but there's not enough space left for a single question. */
                return -EMSGSIZE;
 
        question = dns_question_new(n);
        if (!question)
                return -ENOMEM;
 
        _cleanup_set_free_ Set *keys = NULL; /* references to keys are kept by Question */
 
        keys = set_new(&dns_resource_key_hash_ops);
        if (!keys)
                return log_oom();
 
        /* Pre-allocate the question hashmap, but cap the pre-allocation to a number of questions the
         * packet can realistically contain. That is, pick the minimal value from the claimed number
         * of questions (n) and a maximum number of potential questions the remaining packet data can
         * actually contain, see above.
         *
         * Note for the multiplication: higher multipliers give slightly higher efficiency through
         * hash collisions, but the gains quickly drop off after 2. */
        r = set_reserve(keys, MIN(n, prealloc) * 2);
        if (r < 0)
                return r;
 
        for (unsigned i = 0; i < n; i++) {
                _cleanup_(dns_resource_key_unrefp) DnsResourceKey *key = NULL;
                bool qu;
 
                r = dns_packet_read_key(p, &key, &qu, NULL);
                if (r < 0)
                        return r;
 
                if (!dns_type_is_valid_query(key->type))
                        return -EBADMSG;
 
                r = set_put(keys, key);
                if (r < 0)
                        return r;
                if (r == 0)
                        /* Already in the Question, let's skip */
                        continue;
 
                r = dns_question_add_raw(question, key, qu ? DNS_QUESTION_WANTS_UNICAST_REPLY : 0);
                if (r < 0)
                        return r;
        }
 
        *ret_question = TAKE_PTR(question);
 
        return 0;
}
 
static int dns_packet_extract_answer(DnsPacket *p, DnsAnswer **ret_answer) {
        _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
        unsigned n, prealloc;
        _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *previous = NULL;
        bool bad_opt = false;
        int r;
 
        assert(ret_answer);
 
        n = DNS_PACKET_RRCOUNT(p);
        if (n == 0) {
                *ret_answer = NULL;
                return 0;
        }
 
        /* Calculate the maximum number of potential RRs the remaining packet data can actually contain:
         * p->size - p->rindex are the remaining unread bytes in the packet, and the 11U is the minimum size
         * of each RR - 1 (NAME) + 2 (TYPE) + 2 (CLASS) + 4 (TTL) + 2 (RDLENGTH). */
        prealloc = (p->size - p->rindex) / 11U;
        if (prealloc == 0)
                /* RRCOUNT > 0 but there's not enough space left for a single RR. */
                return -EMSGSIZE;
 
        /* Pre-allocate the answer hashmap, but cap the pre-allocation to a number of RRs the packet can
         * realistically contain. That is, pick the minimal value from the claimed number of RRs (n) and a
         * maximum number of potential RRs the remaining packet data can actually contain, see above. */
        answer = dns_answer_new(MIN(n, prealloc));
        if (!answer)
                return -ENOMEM;
 
        for (unsigned i = 0; i < n; i++) {
                _cleanup_(dns_resource_record_unrefp) DnsResourceRecord *rr = NULL;
                bool cache_flush = false;
                size_t start;
 
                if (p->rindex == p->size && p->opt) {
                        /* If we reached the end of the packet already, but there are still more RRs
                         * declared, then that's a corrupt packet. Let's accept the packet anyway, since it's
                         * apparently a common bug in routers. Let's however suppress OPT support in this
                         * case, so that we force the rest of the logic into lowest DNS baseline support. Or
                         * to say this differently: if the DNS server doesn't even get the RR counts right,
                         * it's highly unlikely it gets EDNS right. */
                        log_debug("More resource records declared in packet than included, suppressing OPT.");
                        bad_opt = true;
                        break;
                }
 
                r = dns_packet_read_rr(p, &rr, &cache_flush, &start);
                if (r < 0)
                        return r;
 
                /* Try to reduce memory usage a bit */
                if (previous)
                        dns_resource_key_reduce(&rr->key, &previous->key);
 
                if (rr->key->type == DNS_TYPE_OPT) {
                        bool has_rfc6975;
 
                        if (p->opt || bad_opt) {
                                /* Multiple OPT RRs? if so, let's ignore all, because there's
                                 * something wrong with the server, and if one is valid we wouldn't
                                 * know which one. */
                                log_debug("Multiple OPT RRs detected, ignoring all.");
                                bad_opt = true;
                                continue;
                        }
 
                        if (!dns_name_is_root(dns_resource_key_name(rr->key))) {
                                /* If the OPT RR is not owned by the root domain, then it is bad,
                                 * let's ignore it. */
                                log_debug("OPT RR is not owned by root domain, ignoring.");
                                bad_opt = true;
                                continue;
                        }
 
                        if (i < DNS_PACKET_ANCOUNT(p) + DNS_PACKET_NSCOUNT(p)) {
                                /* OPT RR is in the wrong section? Some Belkin routers do this. This
                                 * is a hint the EDNS implementation is borked, like the Belkin one
                                 * is, hence ignore it. */
                                log_debug("OPT RR in wrong section, ignoring.");
                                bad_opt = true;
                                continue;
                        }
 
                        if (!opt_is_good(rr, &has_rfc6975)) {
                                log_debug("Malformed OPT RR, ignoring.");
                                bad_opt = true;
                                continue;
                        }
 
                        if (DNS_PACKET_QR(p)) {
                                /* Additional checks for responses */
 
                                if (!DNS_RESOURCE_RECORD_OPT_VERSION_SUPPORTED(rr))
                                        /* If this is a reply and we don't know the EDNS version
                                         * then something is weird... */
                                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                                               "EDNS version newer that our request, bad server.");
 
                                if (has_rfc6975) {
                                        /* If the OPT RR contains RFC6975 algorithm data, then this
                                         * is indication that the server just copied the OPT it got
                                         * from us (which contained that data) back into the reply.
                                         * If so, then it doesn't properly support EDNS, as RFC6975
                                         * makes it very clear that the algorithm data should only
                                         * be contained in questions, never in replies. Crappy
                                         * Belkin routers copy the OPT data for example, hence let's
                                         * detect this so that we downgrade early. */
                                        log_debug("OPT RR contains RFC6975 data, ignoring.");
                                        bad_opt = true;
                                        continue;
                                }
                        }
 
                        p->opt = dns_resource_record_ref(rr);
                        p->opt_start = start;
                        assert(p->rindex >= start);
                        p->opt_size = p->rindex - start;
                } else {
                        DnsAnswerFlags flags = 0;
 
                        if (p->protocol == DNS_PROTOCOL_MDNS) {
                                flags |= DNS_ANSWER_REFUSE_TTL_NO_MATCH;
                                if (!cache_flush)
                                        flags |= DNS_ANSWER_SHARED_OWNER;
                        }
 
                        /* According to RFC 4795, section 2.9. only the RRs from the Answer section shall be
                         * cached. Hence mark only those RRs as cacheable by default, but not the ones from
                         * the Additional or Authority sections.
                         * This restriction does not apply to mDNS records (RFC 6762). */
                        if (i < DNS_PACKET_ANCOUNT(p))
                                flags |= DNS_ANSWER_CACHEABLE|DNS_ANSWER_SECTION_ANSWER;
                        else if (i < DNS_PACKET_ANCOUNT(p) + DNS_PACKET_NSCOUNT(p))
                                flags |= DNS_ANSWER_SECTION_AUTHORITY;
                        else {
                                flags |= DNS_ANSWER_SECTION_ADDITIONAL;
                                if (p->protocol == DNS_PROTOCOL_MDNS)
                                        flags |= DNS_ANSWER_CACHEABLE;
                        }
 
                        r = dns_answer_add(answer, rr, p->ifindex, flags, NULL);
                        if (r < 0)
                                return r;
                }
 
                /* Remember this RR, so that we can potentially merge its ->key object with the
                 * next RR. Note that we only do this if we actually decided to keep the RR around.
                 */
                DNS_RR_REPLACE(previous, dns_resource_record_ref(rr));
        }
 
        if (bad_opt) {
                p->opt = dns_resource_record_unref(p->opt);
                p->opt_start = p->opt_size = SIZE_MAX;
        }
 
        *ret_answer = TAKE_PTR(answer);
 
        return 0;
}
 
int dns_packet_extract(DnsPacket *p) {
        assert(p);
 
        if (p->extracted)
                return 0;
 
        _cleanup_(dns_question_unrefp) DnsQuestion *question = NULL;
        _cleanup_(dns_answer_unrefp) DnsAnswer *answer = NULL;
        _unused_ _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
        int r;
 
        dns_packet_rewind(p, DNS_PACKET_HEADER_SIZE);
 
        r = dns_packet_extract_question(p, &question);
        if (r < 0)
                return r;
 
        r = dns_packet_extract_answer(p, &answer);
        if (r < 0)
                return r;
 
        if (p->rindex < p->size)  {
                log_debug("Trailing garbage in packet, suppressing OPT.");
                p->opt = dns_resource_record_unref(p->opt);
                p->opt_start = p->opt_size = SIZE_MAX;
        }
 
        p->question = TAKE_PTR(question);
        p->answer = TAKE_PTR(answer);
        p->extracted = true;
 
        /* no CANCEL, always rewind */
        return 0;
}
 
int dns_packet_is_reply_for(DnsPacket *p, const DnsResourceKey *key) {
        int r;
 
        assert(p);
        assert(key);
 
        /* Checks if the specified packet is a reply for the specified
         * key and the specified key is the only one in the question
         * section. */
 
        if (DNS_PACKET_QR(p) != 1)
                return 0;
 
        /* Let's unpack the packet, if that hasn't happened yet. */
        r = dns_packet_extract(p);
        if (r < 0)
                return r;
 
        if (!p->question)
                return 0;
 
        if (p->question->n_keys != 1)
                return 0;
 
        return dns_resource_key_equal(dns_question_first_key(p->question), key);
}
 
int dns_packet_patch_max_udp_size(DnsPacket *p, uint16_t max_udp_size) {
        assert(p);
        assert(max_udp_size >= DNS_PACKET_UNICAST_SIZE_MAX);
 
        if (p->opt_start == SIZE_MAX) /* No OPT section, nothing to patch */
                return 0;
 
        assert(p->opt_size != SIZE_MAX);
        assert(p->opt_size >= 5);
 
        unaligned_write_be16(DNS_PACKET_DATA(p) + p->opt_start + 3, max_udp_size);
        return 1;
}
 
static int patch_rr(DnsPacket *p, usec_t age) {
        _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
        size_t ttl_index;
        uint32_t ttl;
        uint16_t type, rdlength;
        int r;
 
        /* Patches the RR at the current rindex, subtracts the specified time from the TTL */
 
        r = dns_packet_read_name(p, NULL, true, NULL);
        if (r < 0)
                return r;
 
        r = dns_packet_read_uint16(p, &type, NULL);
        if (r < 0)
                return r;
 
        r = dns_packet_read_uint16(p, NULL, NULL);
        if (r < 0)
                return r;
 
        r = dns_packet_read_uint32(p, &ttl, &ttl_index);
        if (r < 0)
                return r;
 
        if (type != DNS_TYPE_OPT) { /* The TTL of the OPT field is not actually a TTL, skip it */
                ttl = LESS_BY(ttl * USEC_PER_SEC, age) / USEC_PER_SEC;
                unaligned_write_be32(DNS_PACKET_DATA(p) + ttl_index, ttl);
        }
 
        r = dns_packet_read_uint16(p, &rdlength, NULL);
        if (r < 0)
                return r;
 
        r = dns_packet_read(p, rdlength, NULL, NULL);
        if (r < 0)
                return r;
 
        CANCEL_REWINDER(rewinder);
        return 0;
}
 
int dns_packet_patch_ttls(DnsPacket *p, usec_t timestamp) {
        assert(p);
        assert(timestamp_is_set(timestamp));
 
        /* Adjusts all TTLs in the packet by subtracting the time difference between now and the specified timestamp */
 
        _unused_ _cleanup_(rewind_dns_packet) DnsPacketRewinder rewinder = REWINDER_INIT(p);
        unsigned n;
        usec_t k;
        int r;
 
        k = now(CLOCK_BOOTTIME);
        assert(k >= timestamp);
        k -= timestamp;
 
        dns_packet_rewind(p, DNS_PACKET_HEADER_SIZE);
 
        n = DNS_PACKET_QDCOUNT(p);
        for (unsigned i = 0; i < n; i++) {
                r = dns_packet_read_key(p, NULL, NULL, NULL);
                if (r < 0)
                        return r;
        }
 
        n = DNS_PACKET_RRCOUNT(p);
        for (unsigned i = 0; i < n; i++) {
 
                /* DNS servers suck, hence the RR count is in many servers off. If we reached the end
                 * prematurely, accept that, exit early */
                if (p->rindex == p->size)
                        break;
 
                r = patch_rr(p, k);
                if (r < 0)
                        return r;
        }
 
        return 0;
}
 
static void dns_packet_hash_func(const DnsPacket *s, struct siphash *state) {
        assert(s);
 
        siphash24_compress_typesafe(s->size, state);
        siphash24_compress(DNS_PACKET_DATA((DnsPacket*) s), s->size, state);
}
 
static int dns_packet_compare_func(const DnsPacket *x, const DnsPacket *y) {
        int r;
 
        r = CMP(x->size, y->size);
        if (r != 0)
                return r;
 
        return memcmp(DNS_PACKET_DATA((DnsPacket*) x), DNS_PACKET_DATA((DnsPacket*) y), x->size);
}
 
DEFINE_HASH_OPS(dns_packet_hash_ops, DnsPacket, dns_packet_hash_func, dns_packet_compare_func);
 
bool dns_packet_equal(const DnsPacket *a, const DnsPacket *b) {
        return dns_packet_compare_func(a, b) == 0;
}
 
int dns_packet_ede_rcode(DnsPacket *p, int *ret_ede_rcode, char **ret_ede_msg) {
        const uint8_t *d;
        size_t l;
        int r;
 
        assert(p);
 
        if (!p->opt)
                return -ENOENT;
 
        d = p->opt->opt.data;
        l = p->opt->opt.data_size;
 
        while (l > 0) {
                uint16_t code, length;
 
                if (l < 4U)
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                               "EDNS0 variable part has invalid size.");
 
                code = unaligned_read_be16(d);
                length = unaligned_read_be16(d + 2);
 
                if (l < 4U + length)
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                               "Truncated option in EDNS0 variable part.");
 
                if (code == DNS_EDNS_OPT_EXT_ERROR) {
                        _cleanup_free_ char *msg = NULL;
 
                        if (length < 2U)
                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                                       "EDNS0 truncated EDE info code.");
 
                        r = make_cstring(d + 6, length - 2U, MAKE_CSTRING_ALLOW_TRAILING_NUL, &msg);
                        if (r < 0)
                                return log_debug_errno(r, "Invalid EDE text in opt.");
 
                        if (ret_ede_msg) {