32#define N_DNS_HEADER_LEN 12
35static uint16_t
n_dns_u16(
const unsigned char* msg,
size_t off) {
36 return (uint16_t)(((unsigned)msg[off] << 8) | (unsigned)msg[off + 1]);
39int n_dns_parse_query(
const unsigned char* msg,
size_t len, uint16_t* id_out,
char* qname_out,
size_t qname_sz, uint16_t* qtype_out) {
59 if ((label_len & 0xC0u) != 0)
62 if (off + label_len > len)
66 if (out + 1 >= qname_sz)
68 qname_out[out++] =
'.';
70 for (
unsigned i = 0; i < label_len; i++) {
71 unsigned char c = msg[off + i];
72 if (out + 1 >= qname_sz)
74 if (c >=
'A' && c <=
'Z')
75 c = (
unsigned char)(c + 32);
76 qname_out[out++] = (char)c;
84 qname_out[out] =
'\0';
94int n_dns_build_a_response(
const unsigned char* query,
size_t qlen, uint32_t ipv4_be, uint32_t ttl,
unsigned char* out,
size_t outsz) {
107 label_len = query[qend];
108 if (label_len == 0) {
112 if ((label_len & 0xC0u) != 0)
114 qend += (size_t)label_len + 1;
119 if (outsz < qend + 16)
123 memcpy(out, query, qend);
126 rflags = (uint16_t)(0x8000u | (qflags & 0x7800u) | 0x0400u | (qflags & 0x0100u) | 0x0080u);
127 out[2] = (
unsigned char)(rflags >> 8);
128 out[3] = (
unsigned char)(rflags & 0xFFu);
146 out[pos++] = (
unsigned char)((ttl >> 24) & 0xFFu);
147 out[pos++] = (
unsigned char)((ttl >> 16) & 0xFFu);
148 out[pos++] = (
unsigned char)((ttl >> 8) & 0xFFu);
149 out[pos++] = (
unsigned char)(ttl & 0xFFu);
152 memcpy(out + pos, &ipv4_be, 4);
int n_dns_build_a_response(const unsigned char *query, size_t qlen, uint32_t ipv4_be, uint32_t ttl, unsigned char *out, size_t outsz)
Build a DNS response answering a query's first question with one A record.
int n_dns_parse_query(const unsigned char *msg, size_t len, uint16_t *id_out, char *qname_out, size_t qname_sz, uint16_t *qtype_out)
Parse the header id and the first question (QNAME + QTYPE) of a DNS message.
#define N_DNS_HEADER_LEN
DNS header size in bytes (id, flags, and the four section counts).
static uint16_t n_dns_u16(const unsigned char *msg, size_t off)
Minimal DNS message helpers: parse a query question and build an A-record response.