3e066c7b51abce7e4973009ce8e2f87d82688f8a
[org.ibex.mail.git] / src / org / ibex / mail / DNSUtil.java
1 package org.ibex.mail;
2 import java.io.*;
3 import java.util.*;
4 import java.net.*;
5 import org.ibex.util.*;
6 import org.ibex.net.*;
7 import org.xbill.DNS.*;
8 import org.xbill.DNS.Message;
9 import javax.naming.*;
10 import javax.naming.directory.*;
11
12 public class DNSUtil {
13
14     public static String reverseLookup(InetAddress ip) throws IOException {
15         Resolver res = new ExtendedResolver();
16         Message response =
17             res.send(Message.newQuery(Record.newRecord(ReverseMap.fromAddress(ip), Type.PTR, DClass.IN)));
18         Record[] answers = response.getSectionArray(Section.ANSWER);
19         return answers.length==0 ? null : answers[0].rdataToString();
20     }
21
22     public static InetAddress[] getMailExchangerIPs(String hostName) {
23         InetAddress[] ret;
24         try {
25             Hashtable env = new Hashtable();
26             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
27             DirContext ictx = new InitialDirContext(env);
28             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
29             Attribute attr = attrs.get("MX");
30             if (attr == null) {
31                 ret = new InetAddress[1];
32                 try {
33                     ret[0] = InetAddress.getByName(hostName);
34                     if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
35                     return ret;
36                 } catch (UnknownHostException uhe) {
37                     Log.warn(DNSUtil.class, "no MX hosts or A record for " + hostName);
38                     return new InetAddress[0];
39                 }
40             } else {
41                 ret = new InetAddress[attr.size()];
42                 NamingEnumeration ne = attr.getAll();
43                 for(int i=0; ne.hasMore();) {
44                     String mx = (String)ne.next();
45                     // FIXME we should be sorting here
46                     mx = mx.substring(mx.indexOf(" ") + 1);
47                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
48                     InetAddress ia = InetAddress.getByName(mx);
49                     if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
50                     ret[i++] = ia;
51                 }
52             }
53         } catch (Exception e) {
54             Log.warn(DNSUtil.class, "couldn't find MX host for " + hostName + " due to");
55             Log.warn(DNSUtil.class, e);
56             return new InetAddress[0];
57         }
58         return ret;
59     }
60
61 }