4 * DNS lookup for SMTP sender
11 #include <netinet/in.h>
12 #include <arpa/nameser.h>
14 #include "sysdep_decls.h"
19 #include "internet_addressing.h"
23 * get_smarthosts() checks the Internet configuration for "smarthost"
24 * entries and returns them in the same format as getmx() does -- fill the
25 * buffer with a delimited list of hosts and return the number of hosts.
27 int get_smarthosts(char *mxbuf) {
31 char host[256], type[256];
32 int total_smarthosts = 0;
34 if (inetcfg == NULL) return(0);
37 config_lines = num_tokens(inetcfg, '\n');
38 for (i=0; i<config_lines; ++i) {
39 extract_token(buf, inetcfg, i, '\n');
40 extract_token(host, buf, 0, '|');
41 extract_token(type, buf, 1, '|');
43 if (!strcasecmp(type, "smarthost")) {
50 return(total_smarthosts);
59 * Sort a pile of MX records (struct mx, definted in domain.h) by preference
62 void sort_mxrecs(struct mx *mxrecs, int num_mxrecs) {
64 struct mx hold1, hold2;
66 if (num_mxrecs < 2) return;
69 for (a = num_mxrecs - 2; a >= 0; --a) {
70 for (b = 0; b <= a; ++b) {
71 if (mxrecs[b].pref > mxrecs[b+1].pref) {
73 memcpy(&hold1, &mxrecs[b], sizeof(struct mx));
74 memcpy(&hold2, &mxrecs[b+1], sizeof(struct mx));
75 memcpy(&mxrecs[b], &hold2, sizeof(struct mx));
76 memcpy(&mxrecs[b+1], &hold1, sizeof(struct mx));
87 * Return one or more MX's for a mail destination.
89 * Upon success, it fills 'mxbuf' with one or more MX hosts, separated by
90 * vertical bar characters, and returns the number of hosts as its return
91 * value. If no MX's are found, it returns 0.
94 int getmx(char *mxbuf, char *dest) {
97 unsigned char *startptr, *endptr, *ptr;
98 char expanded_buf[1024];
99 unsigned short pref, type;
104 struct mx *mxrecs = NULL;
107 /* If we're configured to send all mail to a smart-host, then our
108 * job here is really easy.
110 n = get_smarthosts(mxbuf);
111 if (n > 0) return(n);
114 * No smart-host? Look up the best MX for a site.
118 C_IN, T_MX, (unsigned char *)answer, sizeof(answer) );
121 mxrecs = mallok(sizeof(struct mx));
123 strcpy(mxrecs[0].host, dest);
128 /* If we had to truncate, shrink the number to avoid fireworks */
129 if (ret > sizeof(answer))
130 ret = sizeof(answer);
132 hp = (HEADER *)&answer[0];
133 startptr = &answer[0]; /* start and end of buffer */
134 endptr = &answer[ret];
135 ptr = startptr + HFIXEDSZ; /* advance past header */
137 for (qdcount = ntohs(hp->qdcount); qdcount--; ptr += ret + QFIXEDSZ) {
138 if ((ret = dn_skipname(ptr, endptr)) < 0) {
139 lprintf(9, "dn_skipname error\n");
145 memset(expanded_buf, 0, sizeof(expanded_buf));
146 ret = dn_expand(startptr,
156 ptr += INT16SZ + INT32SZ;
165 ret = dn_expand(startptr,
174 if (mxrecs == NULL) {
175 mxrecs = mallok(sizeof(struct mx));
178 mxrecs = reallok(mxrecs,
179 (sizeof(struct mx) * num_mxrecs) );
182 mxrecs[num_mxrecs - 1].pref = pref;
183 strcpy(mxrecs[num_mxrecs - 1].host,
189 sort_mxrecs(mxrecs, num_mxrecs);
192 for (n=0; n<num_mxrecs; ++n) {
193 strcat(mxbuf, mxrecs[n].host);