4 #include <netinet/in.h>
5 #include <arpa/nameser.h>
7 #include "sysdep_decls.h"
12 #include "internet_addressing.h"
16 * get_smarthosts() checks the Internet configuration for "smarthost"
17 * entries and returns them in the same format as getmx() does -- fill the
18 * buffer with a delimited list of hosts and return the number of hosts.
20 int get_smarthosts(char *mxbuf) {
24 char host[256], type[256];
25 int total_smarthosts = 0;
27 if (inetcfg == NULL) return(0);
30 config_lines = num_tokens(inetcfg, '\n');
31 for (i=0; i<config_lines; ++i) {
32 extract_token(buf, inetcfg, i, '\n');
33 extract_token(host, buf, 0, '|');
34 extract_token(type, buf, 1, '|');
36 if (!strcasecmp(type, "smarthost")) {
43 return(total_smarthosts);
52 * Sort a pile of MX records (struct mx, definted in domain.h) by preference
55 void sort_mxrecs(struct mx *mxrecs, int num_mxrecs) {
57 struct mx hold1, hold2;
59 if (num_mxrecs < 2) return;
62 for (a = num_mxrecs - 2; a >= 0; --a) {
63 for (b = 0; b <= a; ++b) {
64 if (mxrecs[b].pref > mxrecs[b+1].pref) {
66 memcpy(&hold1, &mxrecs[b], sizeof(struct mx));
67 memcpy(&hold2, &mxrecs[b+1], sizeof(struct mx));
68 memcpy(&mxrecs[b], &hold2, sizeof(struct mx));
69 memcpy(&mxrecs[b+1], &hold1, sizeof(struct mx));
80 * Return one or more MX's for a mail destination.
82 * Upon success, it fills 'mxbuf' with one or more MX hosts, separated by
83 * vertical bar characters, and returns the number of hosts as its return
84 * value. If no MX's are found, it returns 0.
87 int getmx(char *mxbuf, char *dest) {
90 unsigned char *startptr, *endptr, *ptr;
91 char expanded_buf[1024];
92 unsigned short pref, type;
97 struct mx *mxrecs = NULL;
100 /* If we're configured to send all mail to a smart-host, then our
101 * job here is really easy.
103 n = get_smarthosts(mxbuf);
104 if (n > 0) return(n);
107 * No smart-host? Look up the best MX for a site.
111 C_IN, T_MX, (unsigned char *)answer, sizeof(answer) );
114 lprintf(5, "No MX found\n");
118 /* If we had to truncate, shrink the number to avoid fireworks */
119 if (ret > sizeof(answer))
120 ret = sizeof(answer);
122 hp = (HEADER *)&answer[0];
123 startptr = &answer[0]; /* start and end of buffer */
124 endptr = &answer[ret];
125 ptr = startptr + HFIXEDSZ; /* advance past header */
127 for (qdcount = ntohs(hp->qdcount); qdcount--; ptr += ret + QFIXEDSZ) {
128 if ((ret = dn_skipname(ptr, endptr)) < 0) {
129 lprintf(9, "dn_skipname error\n");
135 memset(expanded_buf, 0, sizeof(expanded_buf));
136 ret = dn_expand(startptr,
146 ptr += INT16SZ + INT32SZ;
155 ret = dn_expand(startptr,
164 if (mxrecs == NULL) {
165 mxrecs = mallok(sizeof(struct mx));
168 mxrecs = reallok(mxrecs,
169 (sizeof(struct mx) * num_mxrecs) );
172 mxrecs[num_mxrecs - 1].pref = pref;
173 strcpy(mxrecs[num_mxrecs - 1].host, expanded_buf);
177 sort_mxrecs(mxrecs, num_mxrecs);
180 for (n=0; n<num_mxrecs; ++n) {
181 strcat(mxbuf, mxrecs[n].host);