| 1 | #include "stralloc.h" |
| 2 | #include "byte.h" |
| 3 | #include "uint16.h" |
| 4 | #include "dns.h" |
| 5 | |
| 6 | static char *q = 0; |
| 7 | |
| 8 | int dns_mx_packet(stralloc *out,const char *buf,unsigned int len) |
| 9 | { |
| 10 | unsigned int pos; |
| 11 | char header[12]; |
| 12 | char pref[2]; |
| 13 | uint16 numanswers; |
| 14 | uint16 datalen; |
| 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_MX)) |
| 28 | if (byte_equal(header + 2,2,DNS_C_IN)) { |
| 29 | if (!dns_packet_copy(buf,len,pos,pref,2)) return -1; |
| 30 | if (!dns_packet_getname(buf,len,pos + 2,&q)) return -1; |
| 31 | if (!stralloc_catb(out,pref,2)) return -1; |
| 32 | if (!dns_domain_todot_cat(out,q)) return -1; |
| 33 | if (!stralloc_0(out)) return -1; |
| 34 | } |
| 35 | pos += datalen; |
| 36 | } |
| 37 | |
| 38 | return 0; |
| 39 | } |
| 40 | |
| 41 | int dns_mx(stralloc *out,const stralloc *fqdn) |
| 42 | { |
| 43 | if (!dns_domain_fromdot(&q,fqdn->s,fqdn->len)) return -1; |
| 44 | if (dns_resolve(q,DNS_T_MX) == -1) return -1; |
| 45 | if (dns_mx_packet(out,dns_resolve_tx.packet,dns_resolve_tx.packetlen) == -1) return -1; |
| 46 | dns_transmit_free(&dns_resolve_tx); |
| 47 | dns_domain_free(&q); |
| 48 | return 0; |
| 49 | } |