4 #include <netinet/in.h>
5 #include <arpa/nameser.h>
7 #include "sysdep_decls.h"
12 #define SMART_HOST "gatekeeper.wdcs.com"
17 * Sort a pile of MX records (struct mx, definted in domain.h) by preference
20 void sort_mxrecs(struct mx *mxrecs, int num_mxrecs) {
22 struct mx hold1, hold2;
24 if (num_mxrecs < 2) return;
27 for (a = num_mxrecs - 2; a >= 0; --a) {
28 for (b = 0; b <= a; ++b) {
29 if (mxrecs[b].pref > mxrecs[b+1].pref) {
31 memcpy(&hold1, &mxrecs[b], sizeof(struct mx));
32 memcpy(&hold2, &mxrecs[b+1], sizeof(struct mx));
33 memcpy(&mxrecs[b], &hold2, sizeof(struct mx));
34 memcpy(&mxrecs[b+1], &hold1, sizeof(struct mx));
45 * Return one or more MX's for a mail destination.
47 * Upon success, it fills 'mxbuf' with one or more MX hosts, separated by
48 * vertical bar characters, and returns the number of hosts as its return
49 * value. If no MX's are found, it returns 0.
52 int getmx(char *mxbuf, char *dest) {
55 unsigned char *startptr, *endptr, *ptr;
56 char expanded_buf[1024];
57 unsigned short pref, type;
62 struct mx *mxrecs = NULL;
65 /* If we're configured to send all mail to a smart-host, then our
66 * job here is really easy.
69 strcpy(mxbuf, SMART_HOST);
73 /* No smart-host? Look up the best MX for a site.
77 C_IN, T_MX, (unsigned char *)answer, sizeof(answer) );
80 lprintf(5, "No MX found\n");
84 /* If we had to truncate, shrink the number to avoid fireworks */
85 if (ret > sizeof(answer))
88 hp = (HEADER *)&answer[0];
89 startptr = &answer[0]; /* start and end of buffer */
90 endptr = &answer[ret];
91 ptr = startptr + HFIXEDSZ; /* advance past header */
93 for (qdcount = ntohs(hp->qdcount); qdcount--; ptr += ret + QFIXEDSZ) {
94 if ((ret = dn_skipname(ptr, endptr)) < 0) {
95 lprintf(9, "dn_skipname error\n");
101 memset(expanded_buf, 0, sizeof(expanded_buf));
102 ret = dn_expand(startptr,
112 ptr += INT16SZ + INT32SZ;
121 ret = dn_expand(startptr,
130 if (mxrecs == NULL) {
131 mxrecs = mallok(sizeof(struct mx));
134 mxrecs = reallok(mxrecs,
135 (sizeof(struct mx) * num_mxrecs) );
138 mxrecs[num_mxrecs - 1].pref = pref;
139 strcpy(mxrecs[num_mxrecs - 1].host, expanded_buf);
143 sort_mxrecs(mxrecs, num_mxrecs);
146 for (n=0; n<num_mxrecs; ++n) {
147 strcat(mxbuf, mxrecs[n].host);