3 #include <netinet/in.h>
4 #include <arpa/nameser.h>
6 #include "sysdep_decls.h"
9 #define SMART_HOST "gatekeeper.wdcs.com"
14 * Sort a pile of MX records (struct mx, definted in domain.h) by preference
17 void sort_mxrecs(struct mx *mxrecs, int num_mxrecs) {
19 struct mx hold1, hold2;
21 if (num_mxrecs < 2) return;
24 for (a = num_mxrecs - 2; a >= 0; --a) {
25 for (b = 0; b <= a; ++b) {
26 if (mxrecs[b].pref > mxrecs[b+1].pref) {
28 memcpy(hold1, mxrefs[b], sizeof(struct mx));
29 memcpy(hold2, mxrefs[b+1], sizeof(struct mx));
30 memcpy(mxrefs[b], hold2, sizeof(struct mx));
31 memcpy(mxrefs[b+1], hold1, sizeof(struct mx));
42 * Return one or more MX's for a mail destination.
44 * Upon success, it fills 'mxbuf' with one or more MX hosts, separated by
45 * vertical bar characters, and returns the number of hosts as its return
46 * value. If no MX's are found, it returns 0.
49 int getmx(char *mxbuf, char *dest) {
52 unsigned char *startptr, *endptr, *ptr;
54 char expanded_buf[1024];
55 unsigned short pref, type;
60 struct mx *mxrecs = NULL;
63 /* If we're configured to send all mail to a smart-host, then our
64 * job here is really easy.
67 strcpy(mxbuf, SMART_HOST);
71 /* No smart-host? Look up the best MX for a site.
75 C_IN, T_MX, (unsigned char *)answer, sizeof(answer) );
78 lprintf(5, "No MX found\n");
82 /* If we had to truncate, shrink the number to avoid fireworks */
83 if (ret > sizeof(answer))
86 hp = (HEADER *)&answer[0];
87 startptr = &answer[0]; /* start and end of buffer */
88 endptr = &answer[ret];
89 ptr = startptr + HFIXEDSZ; /* advance past header */
91 for (qdcount = ntohs(hp->qdcount); qdcount--; ptr += ret + QFIXEDSZ) {
92 if ((ret = dn_skipname(ptr, endptr)) < 0) {
93 lprintf(9, "dn_skipname error\n");
99 memset(expanded_buf, 0, sizeof(expanded_buf));
100 ret = dn_expand(startptr,
110 ptr += INT16SZ + INT32SZ;
119 ret = dn_expand(startptr,
128 if (mxrecs == NULL) {
129 mxrecs = mallok(sizeof(struct mx));
132 mxrecs = reallok(mxrecs,
133 (sizeof(struct mx) * num_mxrecs) );
136 mxrecs[num_mxrecs - 1].pref = pref;
137 strcpy(mxrecs[num_mxrecs - 1].host, expanded_buf);
141 lprintf(9, "unsorted...\n");
142 for (n=0; n<num_mxrecs; ++n)
143 lprintf(9, "%10d %s\n", mxrecs[n].pref, mxrecs[n].host);
144 sort_mxrecs(mxrecs, num_mxrecs);
145 lprintf(9, "sorted...\n");
146 for (n=0; n<num_mxrecs; ++n)
147 lprintf(9, "%10d %s\n", mxrecs[n].pref, mxrecs[n].host);
150 for (n=0; n<num_mxrecs; ++n) {
151 strcat(mxbuf, mxrecs[n].host);