]> Pileus Git - ~andy/fetchmail/blob - mxget.c
7dc2c8fdb938bec1222be6a841d72022f2177d02
[~andy/fetchmail] / mxget.c
1 /*
2  * mxget.c -- fetch MX records for given DNS name
3  *
4  * Copyright 1996 by Eric S. Raymond
5  * All rights reserved.
6  * For license terms, see the file COPYING in this directory.
7  */
8
9 #include "config.h"
10 #ifdef HAVE_GETHOSTBYNAME
11 #include <netdb.h>
12 #include <sys/types.h>
13 #include <netinet/in.h>
14 #include <arpa/nameser.h>
15 #include <resolv.h>
16 #include "mx.h"
17
18 /*
19  * This ought to be in the bind library.  It's adapted from sendmail.
20  */
21
22 struct mxentry *getmxrecords(name)
23 /* get MX records for given host */
24 const char *name;
25 {
26     unsigned char answer[PACKETSZ], MXHostBuf[PACKETSZ], *eom, *cp, *bp;
27     int n, ancount, qdcount, buflen, type, pref, ind;
28     static struct mxentry pmx[(PACKETSZ - HFIXEDSZ) / sizeof(struct mxentry)];
29     HEADER *hp;
30
31     n = res_search(name,C_IN,T_MX,(unsigned char*)&answer, sizeof(answer));
32     if (n == -1)
33         return((struct mxentry *)NULL);
34
35     hp = (HEADER *)&answer;
36     cp = answer + HFIXEDSZ;
37     eom = answer + n;
38     h_errno = 0;
39     for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
40         if ((n = dn_skipname(cp, eom)) < 0)
41             return((struct mxentry *)NULL);
42     buflen = sizeof(MXHostBuf) - 1;
43     bp = MXHostBuf;
44     ind = 0;
45     ancount = ntohs(hp->ancount);
46     while (--ancount >= 0 && cp < eom)
47     {
48         if ((n = dn_expand(answer, eom, cp, bp, buflen)) < 0)
49             break;
50         cp += n;
51         GETSHORT(type, cp);
52         cp += INT16SZ + INT32SZ;
53         GETSHORT(n, cp);
54         if (type != T_MX)
55         {
56             cp += n;
57             continue;
58         }
59         GETSHORT(pref, cp);
60         if ((n = dn_expand(answer, eom, cp, bp, buflen)) < 0)
61             break;
62         cp += n;
63
64         pmx[ind].name = bp;
65         pmx[ind].pref = pref;
66         ++ind;
67
68         n = strlen(bp);
69         bp += n;
70         *bp++ = '\0';
71
72         buflen -= n + 1;
73     }
74
75     pmx[ind].name = (char *)NULL;
76     pmx[ind].pref = -1;
77     return(pmx);
78 }
79 #endif /* HAVE_GETHOSTBYNAME */
80
81 #ifdef TESTMAIN
82 main(int argc, char *argv[])
83 {
84     int count, i;
85     struct mxentry *responses;
86
87     responses = getmxrecords(argv[1]);
88     if (responses == (struct mxentry *)NULL)
89         puts("No MX records found");
90     else
91         do {
92             printf("%s %d\n", responses->name, responses->pref);
93         } while
94             ((++responses)->name);
95 }
96 #endif /* TESTMAIN */
97
98 /* mxget.c ends here */