2 * mxget.c -- fetch MX records for given DNS name
4 * Copyright (C) 1996, 1997, 1998, 2000, 2002 by Eric S. Raymond
5 * Copyright (C) 2005, 2006, 2007 by Matthias Andree
6 * For license terms, see the file COPYING in this directory.
10 #include "fetchmail.h"
13 #ifdef HAVE_RES_SEARCH
14 #ifdef HAVE_NET_SOCKET_H
15 #include <net/socket.h>
18 #include <sys/types.h>
19 #include <netinet/in.h>
22 #include "beos/beos_nameser.h"
25 #ifdef HAVE_ARPA_NAMESER_H
26 #include <arpa/nameser.h>
35 * This ought to be in the bind library. It's adapted from sendmail.
39 * These are defined in RFC833. Some bind interface headers don't declare them.
40 * Ghod help us if they're ever actually incompatible with what's in
41 * the arpa/nameser.h header.
44 #define PACKETSZ 512 /* maximum packet size */
47 #define HFIXEDSZ 12 /* #/bytes of fixed data in header */
50 #define INT32SZ 4 /* for systems without 32-bit ints */
53 #define INT16SZ 2 /* for systems without 16-bit ints */
56 /* minimum possible size of MX record in packet */
57 #define MIN_MX_SIZE 8 /* corresp to "a.com 0" w/ terminating space */
59 struct mxentry *getmxrecords(const char *name)
60 /* get MX records for given host */
62 char answer[PACKETSZ], *eom, *cp, *bp;
63 int n, ancount, qdcount, buflen, type, pref, ind;
64 static struct mxentry pmx[(PACKETSZ - HFIXEDSZ) / MIN_MX_SIZE];
65 static char MXHostBuf[PACKETSZ - HFIXEDSZ];
68 pmx->name = (char *)NULL;
70 n = res_search(name, C_IN,T_MX, (unsigned char *)&answer, sizeof(answer));
72 return((struct mxentry *)NULL);
73 if ((size_t)n > sizeof(answer))
76 hp = (HEADER *)&answer;
77 cp = answer + HFIXEDSZ;
80 for (qdcount = ntohs(hp->qdcount); qdcount--; cp += n + QFIXEDSZ)
81 if ((n = dn_skipname((unsigned char *)cp, (unsigned char *)eom)) < 0)
82 return((struct mxentry *)NULL);
83 buflen = sizeof(MXHostBuf) - 1;
86 ancount = ntohs(hp->ancount);
87 while (--ancount >= 0 && cp < eom)
89 if ((n = dn_expand((unsigned char *)answer, (unsigned char *)eom,
90 (unsigned char *)cp, bp, buflen)) < 0)
94 cp += INT16SZ + INT32SZ;
102 if ((n = dn_expand((unsigned char *)answer, (unsigned char *)eom,
103 (unsigned char *)cp, bp, buflen)) < 0)
108 pmx[ind].pref = pref;
111 n = strlen((const char *)bp);
118 pmx[ind].name = (char *)NULL;
122 #endif /* HAVE_RES_SEARCH */
127 int main(int argc, char *argv[])
129 #ifdef HAVE_RES_SEARCH
130 struct mxentry *responses;
133 if (argc != 2 || 0 == strcmp(argv[1], "-h")) {
134 fprintf(stderr, "Usage: %s domain\n", argv[0]);
138 #ifdef HAVE_RES_SEARCH
139 responses = getmxrecords(argv[1]);
140 if (responses == (struct mxentry *)NULL) {
141 puts("No MX records found");
144 printf("%s %d\n", responses->name, responses->pref);
145 } while ((++responses)->name);
148 puts("This program was compiled without HAS_RES_SEARCH and does nothing.");
153 #endif /* TESTMAIN */
155 /* mxget.c ends here */