4 * DNS lookup for SMTP sender
11 #include <netinet/in.h>
13 #include <arpa/nameser.h>
15 #include "sysdep_decls.h"
20 #include "internet_addressing.h"
24 * get_smarthosts() checks the Internet configuration for "smarthost"
25 * entries and returns them in the same format as getmx() does -- fill the
26 * buffer with a delimited list of hosts and return the number of hosts.
28 int get_smarthosts(char *mxbuf) {
32 char host[SIZ], type[SIZ];
33 int total_smarthosts = 0;
35 if (inetcfg == NULL) return(0);
38 config_lines = num_tokens(inetcfg, '\n');
39 for (i=0; i<config_lines; ++i) {
40 extract_token(buf, inetcfg, i, '\n');
41 extract_token(host, buf, 0, '|');
42 extract_token(type, buf, 1, '|');
44 if (!strcasecmp(type, "smarthost")) {
51 return(total_smarthosts);
60 * Sort a pile of MX records (struct mx, definted in domain.h) by preference
63 void sort_mxrecs(struct mx *mxrecs, int num_mxrecs) {
65 struct mx hold1, hold2;
67 if (num_mxrecs < 2) return;
70 for (a = num_mxrecs - 2; a >= 0; --a) {
71 for (b = 0; b <= a; ++b) {
72 if (mxrecs[b].pref > mxrecs[b+1].pref) {
74 memcpy(&hold1, &mxrecs[b], sizeof(struct mx));
75 memcpy(&hold2, &mxrecs[b+1], sizeof(struct mx));
76 memcpy(&mxrecs[b], &hold2, sizeof(struct mx));
77 memcpy(&mxrecs[b+1], &hold1, sizeof(struct mx));
88 * Return one or more MX's for a mail destination.
90 * Upon success, it fills 'mxbuf' with one or more MX hosts, separated by
91 * vertical bar characters, and returns the number of hosts as its return
92 * value. If no MX's are found, it returns 0.
95 int getmx(char *mxbuf, char *dest) {
98 unsigned char *startptr, *endptr, *ptr;
99 char expanded_buf[1024];
100 unsigned short pref, type;
105 struct mx *mxrecs = NULL;
108 /* If we're configured to send all mail to a smart-host, then our
109 * job here is really easy.
111 n = get_smarthosts(mxbuf);
112 if (n > 0) return(n);
115 * No smart-host? Look up the best MX for a site.
119 C_IN, T_MX, (unsigned char *)answer, sizeof(answer) );
122 mxrecs = mallok(sizeof(struct mx));
124 strcpy(mxrecs[0].host, dest);
129 /* If we had to truncate, shrink the number to avoid fireworks */
130 if (ret > sizeof(answer))
131 ret = sizeof(answer);
133 hp = (HEADER *)&answer[0];
134 startptr = &answer[0]; /* start and end of buffer */
135 endptr = &answer[ret];
136 ptr = startptr + HFIXEDSZ; /* advance past header */
138 for (qdcount = ntohs(hp->qdcount); qdcount--; ptr += ret + QFIXEDSZ) {
139 if ((ret = dn_skipname(ptr, endptr)) < 0) {
140 lprintf(9, "dn_skipname error\n");
146 memset(expanded_buf, 0, sizeof(expanded_buf));
147 ret = dn_expand(startptr,
157 ptr += INT16SZ + INT32SZ;
166 ret = dn_expand(startptr,
175 if (mxrecs == NULL) {
176 mxrecs = mallok(sizeof(struct mx));
179 mxrecs = reallok(mxrecs,
180 (sizeof(struct mx) * num_mxrecs) );
183 mxrecs[num_mxrecs - 1].pref = pref;
184 strcpy(mxrecs[num_mxrecs - 1].host,
190 sort_mxrecs(mxrecs, num_mxrecs);
193 for (n=0; n<num_mxrecs; ++n) {
194 strcat(mxbuf, mxrecs[n].host);