1 #include "stralloc.h"
2 #include "uint16.h"
3 #include "byte.h"
4 #include "dns.h"
5 
dns_txt_packet(stralloc * out,const char * buf,unsigned int len)6 int dns_txt_packet(stralloc *out,const char *buf,unsigned int len)
7 {
8   unsigned int pos;
9   char header[12];
10   uint16 numanswers;
11   uint16 datalen;
12   char ch;
13   unsigned int txtlen;
14   int i;
15 
16   if (!stralloc_copys(out,"")) return -1;
17 
18   pos = dns_packet_copy(buf,len,0,header,12); if (!pos) return -1;
19   uint16_unpack_big(header + 6,&numanswers);
20   pos = dns_packet_skipname(buf,len,pos); if (!pos) return -1;
21   pos += 4;
22 
23   while (numanswers--) {
24     pos = dns_packet_skipname(buf,len,pos); if (!pos) return -1;
25     pos = dns_packet_copy(buf,len,pos,header,10); if (!pos) return -1;
26     uint16_unpack_big(header + 8,&datalen);
27     if (byte_equal(header,2,DNS_T_TXT))
28       if (byte_equal(header + 2,2,DNS_C_IN)) {
29 	if (pos + datalen > len) return -1;
30 	txtlen = 0;
31 	for (i = 0;i < datalen;++i) {
32 	  ch = buf[pos + i];
33 	  if (!txtlen)
34 	    txtlen = (unsigned char) ch;
35 	  else {
36 	    --txtlen;
37 	    if (ch < 32) ch = '?';
38 	    if (ch > 126) ch = '?';
39 	    if (!stralloc_append(out,&ch)) return -1;
40 	  }
41 	}
42       }
43     pos += datalen;
44   }
45 
46   return 0;
47 }
48 
49 static char *q = 0;
50 
dns_txt(stralloc * out,const stralloc * fqdn)51 int dns_txt(stralloc *out,const stralloc *fqdn)
52 {
53   if (!dns_domain_fromdot(&q,fqdn->s,fqdn->len)) return -1;
54   if (dns_resolve(q,DNS_T_TXT) == -1) return -1;
55   if (dns_txt_packet(out,dns_resolve_tx.packet,dns_resolve_tx.packetlen) == -1) return -1;
56   dns_transmit_free(&dns_resolve_tx);
57   dns_domain_free(&q);
58   return 0;
59 }
60