From 45c4953b602962ae7ff335d9a346000f00680952 Mon Sep 17 00:00:00 2001 From: Paul Fertser Date: Sat, 4 Apr 2020 13:25:14 +0300 Subject: [PATCH] dns: explicitly endian-convert all fields in header and question MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit For added type-safety and to avoid possible alignment issues make all conversions explicit. While at it, mark header struct as packed so that its layout is guaranteed to match RFC. Prompted by gcc 8 & 9 warning in dns.c: dns.c:261:2: error: converting a packed ‘struct dns_question’ pointer (alignment 1) to a ‘uint16_t’ {aka ‘short unsigned int’} pointer (alignment 2) may result in an unaligned pointer value [-Werror=address-of-packed-member] 261 | uint16_t *swap = (uint16_t *) q; Signed-off-by: Paul Fertser [Tweak commit message] Acked-by: Kevin Darbyshire-Bryant --- dns.c | 20 ++++++++------------ dns.h | 2 +- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/dns.c b/dns.c index aadfdd8..86e5ea3 100644 --- a/dns.c +++ b/dns.c @@ -237,16 +237,16 @@ static struct dns_header* dns_consume_header(uint8_t **data, int *len) { struct dns_header *h = (struct dns_header *) *data; - uint16_t *swap = (uint16_t *) h; - int endianess = 6; if (*len < sizeof(struct dns_header)) return NULL; - while (endianess--) { - *swap = be16_to_cpu(*swap); - swap++; - } + h->id = be16_to_cpu(h->id); + h->flags = be16_to_cpu(h->flags); + h->questions = be16_to_cpu(h->questions); + h->answers = be16_to_cpu(h->answers); + h->authority = be16_to_cpu(h->authority); + h->additional = be16_to_cpu(h->additional); *len -= sizeof(struct dns_header); *data += sizeof(struct dns_header); @@ -258,16 +258,12 @@ static struct dns_question* dns_consume_question(uint8_t **data, int *len) { struct dns_question *q = (struct dns_question *) *data; - uint16_t *swap = (uint16_t *) q; - int endianess = 2; if (*len < sizeof(struct dns_question)) return NULL; - while (endianess--) { - *swap = be16_to_cpu(*swap); - swap++; - } + q->type = be16_to_cpu(q->type); + q->class = be16_to_cpu(q->class); *len -= sizeof(struct dns_question); *data += sizeof(struct dns_question); diff --git a/dns.h b/dns.h index f1f0212..91570bd 100644 --- a/dns.h +++ b/dns.h @@ -49,7 +49,7 @@ struct dns_header { uint16_t answers; uint16_t authority; uint16_t additional; -}; +} __attribute__((packed)); struct dns_srv_data { uint16_t priority; -- 2.25.1