xref: /third_party/musl/src/network/dns_parse.c (revision 570af302)
1570af302Sopenharmony_ci#include <string.h>
2570af302Sopenharmony_ci#include "lookup.h"
3570af302Sopenharmony_ci
4570af302Sopenharmony_ciint __dns_parse(const unsigned char *r, int rlen, int (*callback)(void *, int, const void *, int, const void *, int), void *ctx)
5570af302Sopenharmony_ci{
6570af302Sopenharmony_ci	int qdcount, ancount;
7570af302Sopenharmony_ci	const unsigned char *p;
8570af302Sopenharmony_ci	int len;
9570af302Sopenharmony_ci
10570af302Sopenharmony_ci	if (rlen<12) return -1;
11570af302Sopenharmony_ci	if ((r[3]&15)) return 0;
12570af302Sopenharmony_ci	p = r+12;
13570af302Sopenharmony_ci	qdcount = r[4]*256 + r[5];
14570af302Sopenharmony_ci	ancount = r[6]*256 + r[7];
15570af302Sopenharmony_ci	while (qdcount--) {
16570af302Sopenharmony_ci		while (p-r < rlen && *p-1U < 127) p++;
17570af302Sopenharmony_ci		if (p>r+rlen-6)
18570af302Sopenharmony_ci			return -1;
19570af302Sopenharmony_ci		p += 5 + !!*p;
20570af302Sopenharmony_ci	}
21570af302Sopenharmony_ci	while (ancount--) {
22570af302Sopenharmony_ci		while (p-r < rlen && *p-1U < 127) p++;
23570af302Sopenharmony_ci		if (p>r+rlen-12)
24570af302Sopenharmony_ci			return -1;
25570af302Sopenharmony_ci		p += 1 + !!*p;
26570af302Sopenharmony_ci		len = p[8]*256 + p[9];
27570af302Sopenharmony_ci		if (len+10 > r+rlen-p) return -1;
28570af302Sopenharmony_ci		if (callback(ctx, p[1], p+10, len, r, rlen) < 0) return -1;
29570af302Sopenharmony_ci		p += 10 + len;
30570af302Sopenharmony_ci	}
31570af302Sopenharmony_ci	return 0;
32570af302Sopenharmony_ci}
33