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 1–1000 of 3,202

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include "alloc-util.h"
#include "bitmap.h"
#include "dns-answer.h"
#include "dns-domain.h"
#include "dns-packet.h"
#include "dns-question.h"
#include "dns-rr.h"
#include "escape.h"
#include "log.h"
#include "memory-util.h"
#include "set.h"
#include "siphash24.h"
#include "stdio-util.h"
#include "string-table.h"
#include "string-util.h"
#include "time-util.h"
#include "unaligned.h"
#include "utf8.h"
 
#define EDNS0_OPT_DO (1<<15)
 
assert_cc(DNS_PACKET_SIZE_START > DNS_PACKET_HEADER_SIZE);
 
typedef struct DnsPacketRewinder {
        DnsPacket *packet;
        size_t saved_rindex;
} DnsPacketRewinder;
 
static void rewind_dns_packet(DnsPacketRewinder *rewinder) {
        if (rewinder->packet)
                dns_packet_rewind(rewinder->packet, rewinder->saved_rindex);
}
 
#define REWINDER_INIT(p) {                              \
                .packet = (p),                          \
                .saved_rindex = (p)->rindex,            \
        }
#define CANCEL_REWINDER(rewinder) do { (rewinder).packet = NULL; } while (0)
 
uint16_t dns_packet_rcode(DnsPacket *p) {
        uint16_t rcode;
 
        assert(p);
 
        if (p->opt)
                rcode = (uint16_t) ((p->opt->ttl >> 20) & 0xFF0);
        else
                rcode = 0;
 
        return rcode | (be16toh(DNS_PACKET_HEADER(p)->flags) & 0xF);
};
 
uint16_t dns_packet_payload_size_max(DnsPacket *p) {
        assert(p);
 
        /* Returns the advertised maximum size for replies, or the DNS default if there's nothing defined. */
 
        if (p->ipproto == IPPROTO_TCP) /* we ignore EDNS(0) size data on TCP, like everybody else */
                return DNS_PACKET_SIZE_MAX;
 
        if (p->opt)
                return MAX(DNS_PACKET_UNICAST_SIZE_MAX, p->opt->key->class);
 
        return DNS_PACKET_UNICAST_SIZE_MAX;
}
 
bool dns_packet_do(DnsPacket *p) {
        assert(p);
 
        if (!p->opt)
                return false;
 
        return !!(p->opt->ttl & (1U << 15));
}
 
bool dns_packet_version_supported(DnsPacket *p) {
        assert(p);
 
        /* Returns true if this packet is in a version we support. Which means either non-EDNS or EDNS(0), but not EDNS
         * of any newer versions */
 
        if (!p->opt)
                return true;
 
        return DNS_RESOURCE_RECORD_OPT_VERSION_SUPPORTED(p->opt);
}
 
int dns_packet_new(
                DnsPacket **ret,
                DnsProtocol protocol,
                size_t min_alloc_dsize,
                size_t max_size) {
 
        DnsPacket *p;
        size_t a;
 
        assert(ret);
        assert(max_size >= DNS_PACKET_HEADER_SIZE);
 
        if (max_size > DNS_PACKET_SIZE_MAX)
                max_size = DNS_PACKET_SIZE_MAX;
 
        /* The caller may not check what is going to be truly allocated, so do not allow to
         * allocate a DNS packet bigger than DNS_PACKET_SIZE_MAX.
         */
        if (min_alloc_dsize > DNS_PACKET_SIZE_MAX)
                return log_error_errno(SYNTHETIC_ERRNO(EFBIG),
                                       "Requested packet data size too big: %zu",
                                       min_alloc_dsize);
 
        /* When dns_packet_new() is called with min_alloc_dsize == 0, allocate more than the
         * absolute minimum (which is the dns packet header size), to avoid
         * resizing immediately again after appending the first data to the packet.
         */
        if (min_alloc_dsize < DNS_PACKET_HEADER_SIZE)
                a = DNS_PACKET_SIZE_START;
        else
                a = min_alloc_dsize;
 
        /* round up to next page size */
        /* Silence static analyzers */
        assert(a <= SIZE_MAX - ALIGN(sizeof(DnsPacket)));
        a = PAGE_ALIGN(ALIGN(sizeof(DnsPacket)) + a) - ALIGN(sizeof(DnsPacket));
 
        /* make sure we never allocate more than useful */
        if (a > max_size)
                a = max_size;
 
        p = malloc0(ALIGN(sizeof(DnsPacket)) + a);
        if (!p)
                return -ENOMEM;
 
        *p = (DnsPacket) {
                .n_ref = 1,
                .protocol = protocol,
                .size = DNS_PACKET_HEADER_SIZE,
                .rindex = DNS_PACKET_HEADER_SIZE,
                .allocated = a,
                .max_size = max_size,
                .opt_start = SIZE_MAX,
                .opt_size = SIZE_MAX,
        };
 
        *ret = p;
 
        return 0;
}
 
void dns_packet_set_flags(DnsPacket *p, bool dnssec_checking_disabled, bool truncated) {
 
        DnsPacketHeader *h;
 
        assert(p);
 
        h = DNS_PACKET_HEADER(p);
 
        switch (p->protocol) {
        case DNS_PROTOCOL_LLMNR:
                assert(!truncated);
 
                h->flags = htobe16(DNS_PACKET_MAKE_FLAGS(0 /* qr */,
                                                         0 /* opcode */,
                                                         0 /* c */,
                                                         0 /* tc */,
                                                         0 /* t */,
                                                         0 /* ra */,
                                                         0 /* ad */,
                                                         0 /* cd */,
                                                         0 /* rcode */));
                break;
 
        case DNS_PROTOCOL_MDNS:
                h->flags = htobe16(DNS_PACKET_MAKE_FLAGS(0         /* qr */,
                                                         0         /* opcode */,
                                                         0         /* aa */,
                                                         truncated /* tc */,
                                                         0         /* rd (ask for recursion) */,
                                                         0         /* ra */,
                                                         0         /* ad */,
                                                         0         /* cd */,
                                                         0         /* rcode */));
                break;
 
        default:
                assert(!truncated);
 
                h->flags = htobe16(DNS_PACKET_MAKE_FLAGS(0 /* qr */,
                                                         0 /* opcode */,
                                                         0 /* aa */,
                                                         0 /* tc */,
                                                         1 /* rd (ask for recursion) */,
                                                         0 /* ra */,
                                                         0 /* ad */,
                                                         dnssec_checking_disabled /* cd */,
                                                         0 /* rcode */));
        }
}
 
int dns_packet_new_query(DnsPacket **ret, DnsProtocol protocol, size_t min_alloc_dsize, bool dnssec_checking_disabled) {
        DnsPacket *p;
        int r;
 
        assert(ret);
 
        r = dns_packet_new(&p, protocol, min_alloc_dsize, DNS_PACKET_SIZE_MAX);
        if (r < 0)
                return r;
 
        /* Always set the TC bit to 0 initially.
         * If there are multiple packets later, we'll update the bit shortly before sending.
         */
        dns_packet_set_flags(p, dnssec_checking_disabled, false);
 
        *ret = p;
        return 0;
}
 
int dns_packet_dup(DnsPacket **ret, DnsPacket *p) {
        DnsPacket *c;
        int r;
 
        assert(ret);
        assert(p);
 
        r = dns_packet_validate(p);
        if (r < 0)
                return r;
 
        /* Silence static analyzers */
        assert(p->size <= SIZE_MAX - ALIGN(sizeof(DnsPacket)));
        c = malloc(ALIGN(sizeof(DnsPacket)) + p->size);
        if (!c)
                return -ENOMEM;
 
        *c = (DnsPacket) {
                .n_ref = 1,
                .protocol = p->protocol,
                .size = p->size,
                .rindex = DNS_PACKET_HEADER_SIZE,
                .allocated = p->size,
                .max_size = p->max_size,
                .opt_start = SIZE_MAX,
                .opt_size = SIZE_MAX,
        };
 
        memcpy(DNS_PACKET_DATA(c), DNS_PACKET_DATA(p), p->size);
 
        *ret = c;
        return 0;
}
 
DnsPacket *dns_packet_ref(DnsPacket *p) {
 
        if (!p)
                return NULL;
 
        assert(!p->on_stack);
 
        assert(p->n_ref > 0);
        p->n_ref++;
        return p;
}
 
static void dns_packet_free(DnsPacket *p) {
        char *s;
 
        assert(p);
 
        dns_question_unref(p->question);
        dns_answer_unref(p->answer);
        dns_resource_record_unref(p->opt);
 
        while ((s = hashmap_steal_first_key(p->names)))
                free(s);
        hashmap_free(p->names);
 
        free(p->_data);
 
        if (!p->on_stack)
                free(p);
}
 
DnsPacket *dns_packet_unref(DnsPacket *p) {
        if (!p)
                return NULL;
 
        assert(p->n_ref > 0);
 
        if (p->n_ref == 1) {
                dns_packet_unref(p->more);
                dns_packet_free(p);
        } else
                p->n_ref--;
 
        return NULL;
}
 
int dns_packet_validate(DnsPacket *p) {
        assert(p);
 
        if (p->size < DNS_PACKET_HEADER_SIZE)
                return -EBADMSG;
 
        if (p->size > DNS_PACKET_SIZE_MAX)
                return -EBADMSG;
 
        return 1;
}
 
int dns_packet_validate_reply(DnsPacket *p) {
        int r;
 
        assert(p);
 
        r = dns_packet_validate(p);
        if (r < 0)
                return r;
 
        if (DNS_PACKET_QR(p) != 1)
                return 0;
 
        if (DNS_PACKET_OPCODE(p) != 0)
                return -EBADMSG;
 
        switch (p->protocol) {
 
        case DNS_PROTOCOL_LLMNR:
                /* RFC 4795, Section 2.1.1. says to discard all replies with QDCOUNT != 1 */
                if (DNS_PACKET_QDCOUNT(p) != 1)
                        return -EBADMSG;
 
                break;
 
        case DNS_PROTOCOL_MDNS:
                /* RFC 6762, Section 18 */
                if (dns_packet_rcode(p) != 0)
                        return -EBADMSG;
 
                break;
 
        default:
                ;
        }
 
        return 1;
}
 
int dns_packet_validate_query(DnsPacket *p) {
        int r;
 
        assert(p);
 
        r = dns_packet_validate(p);
        if (r < 0)
                return r;
 
        if (DNS_PACKET_QR(p) != 0)
                return 0;
 
        if (DNS_PACKET_OPCODE(p) != 0)
                return -EBADMSG;
 
        switch (p->protocol) {
 
        case DNS_PROTOCOL_DNS:
                if (DNS_PACKET_TC(p))
                        return -EBADMSG;
 
                if (DNS_PACKET_QDCOUNT(p) != 1)
                        return -EBADMSG;
 
                if (DNS_PACKET_ANCOUNT(p) > 0)
                        return -EBADMSG;
 
                /* Note, in most cases, DNS query packet does not have authority section. But some query
                 * types, e.g. IXFR, have Authority sections. Hence, unlike the check for LLMNR, we do not
                 * check DNS_PACKET_NSCOUNT(p) here. */
                break;
 
        case DNS_PROTOCOL_LLMNR:
                if (DNS_PACKET_TC(p))
                        return -EBADMSG;
 
                /* RFC 4795, Section 2.1.1. says to discard all queries with QDCOUNT != 1 */
                if (DNS_PACKET_QDCOUNT(p) != 1)
                        return -EBADMSG;
 
                /* RFC 4795, Section 2.1.1. says to discard all queries with ANCOUNT != 0 */
                if (DNS_PACKET_ANCOUNT(p) > 0)
                        return -EBADMSG;
 
                /* RFC 4795, Section 2.1.1. says to discard all queries with NSCOUNT != 0 */
                if (DNS_PACKET_NSCOUNT(p) > 0)
                        return -EBADMSG;
 
                break;
 
        case DNS_PROTOCOL_MDNS:
                /* Note, mDNS query may have truncation flag. So, unlike the check for DNS and LLMNR,
                 * we do not check DNS_PACKET_TC(p) here. */
 
                /* RFC 6762, Section 18 specifies that messages with non-zero RCODE
                 * must be silently ignored, and that we must ignore the values of
                 * AA, RD, RA, AD, and CD bits. */
                if (dns_packet_rcode(p) != 0)
                        return -EBADMSG;
 
                break;
 
        default:
                ;
        }
 
        return 1;
}
 
static int dns_packet_extend(DnsPacket *p, size_t add, void **ret, size_t *start) {
        assert(p);
 
        if (p->size + add > p->allocated) {
                size_t a, ms;
 
                a = PAGE_ALIGN((p->size + add) * 2);
 
                ms = dns_packet_size_max(p);
                if (a > ms)
                        a = ms;
 
                if (p->size + add > a)
                        return -EMSGSIZE;
 
                if (p->_data) {
                        void *d;
 
                        d = realloc(p->_data, a);
                        if (!d)
                                return -ENOMEM;
 
                        p->_data = d;
                } else {
                        p->_data = malloc(a);
                        if (!p->_data)
                                return -ENOMEM;
 
                        memcpy(p->_data, (uint8_t*) p + ALIGN(sizeof(DnsPacket)), p->size);
                        memzero((uint8_t*) p->_data + p->size, a - p->size);
                }
 
                p->allocated = a;
        }
 
        if (start)
                *start = p->size;
 
        if (ret)
                *ret = DNS_PACKET_DATA(p) + p->size;
 
        p->size += add;
        return 0;
}
 
void dns_packet_truncate(DnsPacket *p, size_t sz) {
        char *s;
        void *n;
 
        assert(p);
 
        if (p->size <= sz)
                return;
 
        HASHMAP_FOREACH_KEY(n, s, p->names) {
 
                if (PTR_TO_SIZE(n) < sz)
                        continue;
 
                hashmap_remove(p->names, s);
                free(s);
        }
 
        p->size = sz;
}
 
int dns_packet_append_blob(DnsPacket *p, const void *d, size_t l, size_t *start) {
        void *q;
        int r;
 
        assert(p);
 
        r = dns_packet_extend(p, l, &q, start);
        if (r < 0)
                return r;
 
        memcpy_safe(q, d, l);
        return 0;
}
 
int dns_packet_append_uint8(DnsPacket *p, uint8_t v, size_t *start) {
        void *d;
        int r;
 
        assert(p);
 
        r = dns_packet_extend(p, sizeof(uint8_t), &d, start);
        if (r < 0)
                return r;
 
        ((uint8_t*) d)[0] = v;
 
        return 0;
}
 
int dns_packet_append_uint16(DnsPacket *p, uint16_t v, size_t *start) {
        void *d;
        int r;
 
        assert(p);
 
        r = dns_packet_extend(p, sizeof(uint16_t), &d, start);
        if (r < 0)
                return r;
 
        unaligned_write_be16(d, v);
 
        return 0;
}
 
int dns_packet_append_uint32(DnsPacket *p, uint32_t v, size_t *start) {
        void *d;
        int r;
 
        assert(p);
 
        r = dns_packet_extend(p, sizeof(uint32_t), &d, start);
        if (r < 0)
                return r;
 
        unaligned_write_be32(d, v);
 
        return 0;
}
 
int dns_packet_append_string(DnsPacket *p, const char *s, size_t *start) {
        assert(p);
        assert(s);
 
        return dns_packet_append_raw_string(p, s, strlen(s), start);
}
 
int dns_packet_append_raw_string(DnsPacket *p, const void *s, size_t size, size_t *start) {
        void *d;
        int r;
 
        assert(p);
        assert(s || size == 0);
 
        if (size > 255)
                return -E2BIG;
 
        r = dns_packet_extend(p, 1 + size, &d, start);
        if (r < 0)
                return r;
 
        ((uint8_t*) d)[0] = (uint8_t) size;
 
        memcpy_safe(((uint8_t*) d) + 1, s, size);
 
        return 0;
}
 
int dns_packet_append_label(DnsPacket *p, const char *d, size_t l, bool canonical_candidate, size_t *start) {
        uint8_t *w;
        int r;
 
        /* Append a label to a packet. Optionally, does this in DNSSEC
         * canonical form, if this label is marked as a candidate for
         * it, and the canonical form logic is enabled for the
         * packet */
 
        assert(p);
        assert(d);
 
        if (l > DNS_LABEL_MAX)
                return -E2BIG;
 
        r = dns_packet_extend(p, 1 + l, (void**) &w, start);
        if (r < 0)
                return r;
 
        *(w++) = (uint8_t) l;
 
        if (p->canonical_form && canonical_candidate)
                /* Generate in canonical form, as defined by DNSSEC
                 * RFC 4034, Section 6.2, i.e. all lower-case. */
                for (size_t i = 0; i < l; i++)
                        w[i] = (uint8_t) ascii_tolower(d[i]);
        else
                /* Otherwise, just copy the string unaltered. This is
                 * essential for DNS-SD, where the casing of labels
                 * matters and needs to be retained. */
                memcpy(w, d, l);
 
        return 0;
}
 
int dns_packet_append_name(
                DnsPacket *p,
                const char *name,
                bool allow_compression,
                bool canonical_candidate,
                size_t *start) {
 
        _cleanup_free_ char **added_entries = NULL; /* doesn't own the strings! this is just regular pointer array, not a NULL-terminated strv! */
        size_t n_added_entries = 0, saved_size;
        int r;
 
        assert(p);
        assert(name);
 
        r = dns_name_is_valid(name);
        if (r < 0)
                return r;
        if (r == 0)
                return -EINVAL;
 
        if (p->refuse_compression)
                allow_compression = false;
 
        saved_size = p->size;
 
        while (!dns_name_is_root(name)) {
                const char *z = name;
                char label[DNS_LABEL_MAX+1];
                size_t n = 0, offset;
 
                if (allow_compression)
                        n = PTR_TO_SIZE(hashmap_get(p->names, name));
                /* Only pointer-expressible offsets of already-appended labels enter the map below,
                 * so both bounds should hold. Control flow and not assert(), which is no check at
                 * all under -Db_ndebug=true, for bounds that decide what goes on the wire.
                 * saved_size, not p->size: RFC 1035 § 4.1.4 allows a pointer only to a prior
                 * occurrence, which is what dns_packet_read_name() enforces on the way in. */
                if (n > 0 && n <= DNS_COMPRESSION_OFFSET_MAX && n < saved_size) {
                        r = dns_packet_append_uint16(p, DNS_COMPRESSION_POINTER_FLAG | n, NULL);
                        if (r < 0)
                                goto fail;
 
                        goto done;
                }
 
                r = dns_label_unescape(&name, label, sizeof label, 0);
                if (r < 0)
                        goto fail;
 
                r = dns_packet_append_label(p, label, r, canonical_candidate, &offset);
                if (r < 0)
                        goto fail;
 
                /* Remember the name for compression -- but only if this occurrence sits within the
                 * 14 bits an RFC 1035 pointer can express. An offset beyond that can never be
                 * referenced, so it doesn't belong in the map: it would only collide with a later
                 * occurrence of the same name, needlessly failing the whole append with -EEXIST. */
                if (allow_compression && offset <= DNS_COMPRESSION_OFFSET_MAX) {
                        _cleanup_free_ char *s = NULL;
 
                        if (!GREEDY_REALLOC(added_entries, n_added_entries + 1)) {
                                r = -ENOMEM;
                                goto fail;
                        }
 
                        s = strdup(z);
                        if (!s) {
                                r = -ENOMEM;
                                goto fail;
                        }
 
                        r = hashmap_ensure_put(&p->names, &dns_name_hash_ops, s, SIZE_TO_PTR(offset));
                        if (r < 0)
                                goto fail;
 
                        /* Keep track of the entries we just added (note that the string is owned by the hashtable, not this array!) */
                        added_entries[n_added_entries++] = TAKE_PTR(s);
                }
        }
 
        r = dns_packet_append_uint8(p, 0, NULL);
        if (r < 0)
                goto fail;
 
done:
        if (start)
                *start = saved_size;
 
        return 0;
 
fail:
        /* Remove all label compression names we added again */
        FOREACH_ARRAY(s, added_entries, n_added_entries) {
                hashmap_remove(p->names, *s);
                free(*s);
        }
 
        dns_packet_truncate(p, saved_size);
        return r;
}
 
int dns_packet_append_key(DnsPacket *p, const DnsResourceKey *k, const DnsAnswerFlags flags, size_t *start) {
        size_t saved_size;
        uint16_t class;
        int r;
 
        assert(p);
        assert(k);
 
        saved_size = p->size;
 
        r = dns_packet_append_name(p, dns_resource_key_name(k), true, true, NULL);
        if (r < 0)
                goto fail;
 
        r = dns_packet_append_uint16(p, k->type, NULL);
        if (r < 0)
                goto fail;
 
        /* Bit 15 of the CLASS field of an RR is the cache-flush bit in mDNS only, and the rules for setting
         * it apply to responses and announcements only, see RFC 6762, section 10.2. In unicast DNS it is
         * part of the class value itself. Hence set it neither in unicast DNS packets (the RR might come
         * from our mDNS zone, but be sent out via the DNS stub), nor in mDNS queries (the Authority Section
         * of probes is filled from our mDNS zone too, see section 8.2). */
        class = p->protocol == DNS_PROTOCOL_MDNS && DNS_PACKET_QR(p) && FLAGS_SET(flags, DNS_ANSWER_CACHE_FLUSH) ?
                        k->class | MDNS_RR_CACHE_FLUSH_OR_QU : k->class;
        r = dns_packet_append_uint16(p, class, NULL);
        if (r < 0)
                goto fail;
 
        if (start)
                *start = saved_size;
 
        return 0;
 
fail:
        dns_packet_truncate(p, saved_size);
        return r;
}
 
static int dns_packet_append_type_window(DnsPacket *p, uint8_t window, uint8_t length, const uint8_t *types, size_t *start) {
        size_t saved_size;
        int r;
 
        assert(p);
        assert(types);
        assert(length > 0);
 
        saved_size = p->size;
 
        r = dns_packet_append_uint8(p, window, NULL);
        if (r < 0)
                goto fail;
 
        r = dns_packet_append_uint8(p, length, NULL);
        if (r < 0)
                goto fail;
 
        r = dns_packet_append_blob(p, types, length, NULL);
        if (r < 0)
                goto fail;
 
        if (start)
                *start = saved_size;
 
        return 0;
fail:
        dns_packet_truncate(p, saved_size);
        return r;
}
 
static int dns_packet_append_types(DnsPacket *p, Bitmap *types, size_t *start) {
        uint8_t window = 0;
        uint8_t entry = 0;
        uint8_t bitmaps[32] = {};
        unsigned n;
        size_t saved_size;
        int r;
 
        assert(p);
 
        saved_size = p->size;
 
        BITMAP_FOREACH(n, types) {
                assert(n <= 0xffff);
 
                if ((n >> 8) != window && bitmaps[entry / 8] != 0) {
                        r = dns_packet_append_type_window(p, window, entry / 8 + 1, bitmaps, NULL);
                        if (r < 0)
                                goto fail;
 
                        zero(bitmaps);
                }
 
                window = n >> 8;
                entry = n & 255;
 
                bitmaps[entry / 8] |= 1 << (7 - (entry % 8));
        }
 
        if (bitmaps[entry / 8] != 0) {
                r = dns_packet_append_type_window(p, window, entry / 8 + 1, bitmaps, NULL);
                if (r < 0)
                        goto fail;
        }
 
        if (start)
                *start = saved_size;
 
        return 0;
fail:
        dns_packet_truncate(p, saved_size);
        return r;
}
 
/* Append the OPT pseudo-RR described in RFC6891 */
int dns_packet_append_opt(
                DnsPacket *p,
                uint16_t max_udp_size,
                bool edns0_do,
                bool include_rfc6975,
                const char *nsid,
                int rcode,
                size_t *ret_start) {
 
        size_t saved_size;
        int r;
 
        assert(p);
        /* we must never advertise supported packet size smaller than the legacy max */
        assert(max_udp_size >= DNS_PACKET_UNICAST_SIZE_MAX);
        assert(rcode >= 0);
        assert(rcode <= _DNS_RCODE_MAX);
 
        if (p->opt_start != SIZE_MAX)
                return -EBUSY;
 
        assert(p->opt_size == SIZE_MAX);
 
        saved_size = p->size;
 
        /* empty name */
        r = dns_packet_append_uint8(p, 0, NULL);
        if (r < 0)
                return r;
 
        /* type */
        r = dns_packet_append_uint16(p, DNS_TYPE_OPT, NULL);
        if (r < 0)
                goto fail;
 
        /* class: maximum udp packet that can be received */
        r = dns_packet_append_uint16(p, max_udp_size, NULL);
        if (r < 0)
                goto fail;
 
        /* extended RCODE and VERSION */
        r = dns_packet_append_uint16(p, ((uint16_t) rcode & 0x0FF0) << 4, NULL);
        if (r < 0)
                goto fail;
 
        /* flags: DNSSEC OK (DO), see RFC3225 */
        r = dns_packet_append_uint16(p, edns0_do ? EDNS0_OPT_DO : 0, NULL);
        if (r < 0)
                goto fail;
 
        if (edns0_do && include_rfc6975) {
                /* If DO is on and this is requested, also append RFC6975 Algorithm data. This is supposed to
                 * be done on queries, not on replies, hencer callers should turn this off when finishing off
                 * replies. */
 
                static const uint8_t rfc6975[] = {
 
                        0, DNS_EDNS_OPT_DAU, /* OPTION_CODE */
#if HAVE_OPENSSL
                        0, 7, /* LIST_LENGTH */
#else
                        0, 6, /* LIST_LENGTH */
#endif
                        DNSSEC_ALGORITHM_RSASHA1,
                        DNSSEC_ALGORITHM_RSASHA1_NSEC3_SHA1,
                        DNSSEC_ALGORITHM_RSASHA256,
                        DNSSEC_ALGORITHM_RSASHA512,
                        DNSSEC_ALGORITHM_ECDSAP256SHA256,
                        DNSSEC_ALGORITHM_ECDSAP384SHA384,
#if HAVE_OPENSSL
                        DNSSEC_ALGORITHM_ED25519,
#endif
 
                        0, DNS_EDNS_OPT_DHU, /* OPTION_CODE */
                        0, 3, /* LIST_LENGTH */
                        DNSSEC_DIGEST_SHA1,
                        DNSSEC_DIGEST_SHA256,
                        DNSSEC_DIGEST_SHA384,
 
                        0, DNS_EDNS_OPT_N3U, /* OPTION_CODE */
                        0, 1, /* LIST_LENGTH */
                        NSEC3_ALGORITHM_SHA1,
                };
 
                r = dns_packet_append_uint16(p, sizeof(rfc6975), NULL); /* RDLENGTH */
                if (r < 0)
                        goto fail;
 
                r = dns_packet_append_blob(p, rfc6975, sizeof(rfc6975), NULL); /* the payload, as defined above */
 
        } else if (nsid) {
 
                if (strlen(nsid) > UINT16_MAX - 4) {
                        r = -E2BIG;
                        goto fail;
                }
 
                r = dns_packet_append_uint16(p, 4 + strlen(nsid), NULL); /* RDLENGTH */
                if (r < 0)
                        goto fail;
 
                r = dns_packet_append_uint16(p, 3, NULL); /* OPTION-CODE: NSID */
                if (r < 0)
                        goto fail;
 
                r = dns_packet_append_uint16(p, strlen(nsid), NULL); /* OPTION-LENGTH */
                if (r < 0)
                        goto fail;
 
                r = dns_packet_append_blob(p, nsid, strlen(nsid), NULL);
        } else
                r = dns_packet_append_uint16(p, 0, NULL);
        if (r < 0)
                goto fail;
 
        DNS_PACKET_HEADER(p)->arcount = htobe16(DNS_PACKET_ARCOUNT(p) + 1);
 
        p->opt_start = saved_size;
        p->opt_size = p->size - saved_size;
 
        if (ret_start)
                *ret_start = saved_size;
 
        return 0;
 
fail:
        dns_packet_truncate(p, saved_size);
        return r;
}
 
int dns_packet_truncate_opt(DnsPacket *p) {
        assert(p);
 
        if (p->opt_start == SIZE_MAX) {
                assert(p->opt_size == SIZE_MAX);
                return 0;
        }
 
        assert(p->opt_size != SIZE_MAX);
        assert(DNS_PACKET_ARCOUNT(p) > 0);
 
        if (p->opt_start + p->opt_size != p->size)
                return -EBUSY;
 
        dns_packet_truncate(p, p->opt_start);
        DNS_PACKET_HEADER(p)->arcount = htobe16(DNS_PACKET_ARCOUNT(p) - 1);
        p->opt_start = p->opt_size = SIZE_MAX;
 
        return 1;
}
 
int dns_packet_truncate_rrs(DnsPacket *p, size_t max_size, bool reserve_opt) {
        const size_t opt_min_size = 1 + 2 + 2 + 4 + 2; /* Root name, TYPE, CLASS, TTL, RDLENGTH */
        unsigned n_rr = 0, n_an, n_ns, n_ar;
        size_t end, opt_move_size = 0;
        bool opt_kept = false;
        int r;
 
        assert(p);
 
        /* Cut after the last complete RR that fits into max_size. As compression pointers only point
         * backwards, any such prefix stays valid. The OPT RR is usually last, hence if requested reserve
         * room for it and move it behind the prefix. */
 
        dns_packet_rewind(p, DNS_PACKET_HEADER_SIZE);
 
        for (unsigned i = 0; i < DNS_PACKET_QDCOUNT(p); i++) {
                r = dns_packet_read_key(p, /* ret= */ NULL, /* ret_cache_flush_or_qu= */ NULL,
                                        /* ret_start= */ NULL);
                if (r < 0)
                        return r;
        }
 
        end = p->rindex;
        if (end > max_size)
                return -EMSGSIZE;
 
        /* Only move the OPT RR if its owner is the literal root name, i.e. the single zero byte of the empty