use reverse DNS for EHLO/HELO
[org.ibex.mail.git] / src / org / ibex / mail / SMTP.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.mail;
6 import org.ibex.mail.target.*;
7 import org.ibex.util.*;
8 import org.ibex.net.*;
9 import org.ibex.io.*;
10 import java.net.*;
11 import java.io.*;
12 import java.util.*;
13 import java.text.*;
14 import javax.naming.*;
15 import javax.naming.directory.*;
16
17 // FIXME: inbound throttling/ratelimiting
18
19 // "Address enumeration detection" -- notice when it looks like somebody
20 // is trying a raft of addresses.
21
22 // RFC's implemented
23 // RFC2554: SMTP Service Extension for Authentication
24 //     - did not implement section 5, though
25 // RFC4616: SASL PLAIN
26
27 // Note: we can't actually use status codes for feedback if we accept
28 // multiple destination addresses...  a failure on one and success on
29 // the other...
30
31 // FIXME: logging: current logging sucks
32 // FIXME: loop prevention
33 // FIXME: probably need some throttling on outbound mail
34
35 // FEATURE: public static boolean validate(Address a)
36 // FEATURE: rate-limiting
37
38 // FEATURE: infer messageid, date, if not present (?)
39 // FEATURE: exponential backoff on retry time?
40 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
41 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
42 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
43 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
44 public class SMTP {
45
46     public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
47     public static final int numOutgoingThreads = 5;
48
49     private static final SqliteMailbox allmail =
50         (SqliteMailbox)FileBasedMailbox
51         .getFileBasedMailbox("/afs/megacz.com/mail/user/megacz/allmail", false);
52
53     public static final int GRAYLIST_MINWAIT =  1000 * 60 * 60;           // one hour
54     public static final int GRAYLIST_MAXWAIT =  1000 * 60 * 60 * 24 * 5;  // five days
55
56     public static final int RETRY_TIME = 1000 * 60 * 30;
57
58     public static final Graylist graylist;
59     public static final Whitelist whitelist;
60     static {
61         try {
62             graylist =  new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite");
63             whitelist = new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite");
64         } catch (Exception e) {
65             throw new RuntimeException(e);
66         }
67     }
68
69     public static final int MAX_MESSAGE_SIZE =
70         Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
71
72     private static final Mailbox spool =
73         FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true).getMailbox();
74
75     static {
76         for(int i=0; i<numOutgoingThreads; i++)
77             new Outgoing().start();
78     }
79
80     public static void enqueue(Message m) throws IOException {
81         if (!m.envelopeTo.isLocal()) Outgoing.enqueue(m);
82         else {
83             try {
84                 allmail.accept(m);
85             } catch (Exception e) {
86                 // FIXME incredibly gross hack
87                 if (e.toString().indexOf("attempt to insert two messages with identical messageid")==-1)
88                     Log.error(SMTP.class, e);
89             }
90             Target.root.accept(m);
91         }
92     }
93
94     public static class SMTPException extends MailException {
95         int code;
96         String message;
97         public SMTPException(String s) {
98             try {
99                 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
100                 message = s.substring(s.indexOf(' ')+1);
101             } catch (NumberFormatException nfe) {
102                 code = -1;
103                 message = s;
104             }
105         }
106         public String toString() { return "SMTP " + code + ": " + message; }
107         public String getMessage() { return toString(); }
108     }
109
110     // Server //////////////////////////////////////////////////////////////////////////////
111
112     public static class Server {
113         public void handleRequest(Connection conn) throws IOException {
114             conn.setTimeout(5 * 60 * 1000);
115             conn.setNewline("\r\n");
116             conn.println("220 " + conn.vhost + " ESMTP " + this.getClass().getName());
117             Address from = null;
118             Vector to = new Vector();
119             boolean ehlo = false;
120             String remotehost = null;
121             String authenticatedAs = null;
122             int failedRcptCount = 0;
123             for(String command = conn.readln(); ; command = conn.readln()) try {
124                 if (command == null) return;
125                 Log.warn("**"+conn.getRemoteAddress()+"**", command);
126                 String c = command.toUpperCase();
127                 if (c.startsWith("HELO"))        {
128                     remotehost = c.substring(5).trim();
129                     conn.println("250 HELO " + conn.vhost);
130                     from = null; to = new Vector();
131                 } else if (c.startsWith("EHLO")) {
132                     remotehost = c.substring(5).trim();
133                     conn.println("250-"+conn.vhost);
134                     //conn.println("250-AUTH");
135                     conn.println("250-AUTH PLAIN");
136                     //conn.println("250-STARTTLS");
137                     conn.println("250 HELP");
138                     ehlo = true;     
139                     from = null; to = new Vector();
140                 } else if (c.startsWith("RSET")) { conn.println("250 reset ok");           from = null; to = new Vector();
141                 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help.  see a trained professional.");
142                 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
143                 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
144                 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
145                 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
146                 } else if (c.startsWith("STARTTLS")) {
147                     conn.println("220 starting TLS...");
148                     conn.flush();
149                     conn = conn.negotiateSSL(true);
150                     from = null; to = new Vector();
151                 } else if (c.startsWith("AUTH")) {
152                     if (authenticatedAs != null) {
153                         conn.println("503 you are already authenticated; you must reconnect to reauth");
154                     } else {
155                         String mechanism = command.substring(4).trim();
156                         String rest = "";
157                         if (mechanism.indexOf(' ')!=-1) {
158                             rest      = mechanism.substring(mechanism.indexOf(' ')+1).trim();
159                             mechanism = mechanism.substring(0, mechanism.indexOf(' '));
160                         }
161                         if (mechanism.equals("PLAIN")) {
162                             // 538 Encryption required for requested authentication mechanism?
163                             byte[] bytes = Encode.fromBase64(rest);
164                             String authenticateUser = null;
165                             String authorizeUser = null;
166                             String password = null;
167                             int start = 0;
168                             for(int i=0; i<=bytes.length; i++) {
169                                 if (i<bytes.length && bytes[i]!=0) continue;
170                                 String result = new String(bytes, start, i-start, "UTF-8");
171                                 if (authenticateUser==null)   authenticateUser = result;
172                                 else if (authorizeUser==null) authorizeUser = result;
173                                 else if (password==null)      password = result;
174                                 start = i+1;
175                             }
176                             // FIXME: be smarter here
177                             if (Main.auth.login(authorizeUser, password)!=null)
178                                 authenticatedAs = authenticateUser;
179                             conn.println("235 Authentication successful");
180                             /*
181                         } else if (mechanism.equals("CRAM-MD5")) {
182                             String challenge = ;
183                             conn.println("334 "+challenge);
184                             String resp = conn.readln();
185                             if (resp.equals("*")) {
186                                 conn.println("501 client requested AUTH cancellation");
187                             }
188                         } else if (mechanism.equals("ANONYMOUS")) {
189                         } else if (mechanism.equals("EXTERNAL")) {
190                         } else if (mechanism.equals("DIGEST-MD5")) {
191                             */
192                         } else {
193                             conn.println("504 unrecognized authentication type");
194                         }
195                         // on success, reset to initial state; client will EHLO again
196                         from = null; to = new Vector();
197                     }
198                 } else if (c.startsWith("MAIL FROM:")) {
199                     command = command.substring(10).trim();
200                     from = command.equals("<>") ? null : new Address(command);
201                     conn.println("250 " + from + " is syntactically correct");
202                     // Don't perform SAV; discouraged here
203                     //   http://blog.fastmail.fm/2007/12/05/sending-email-servers-best-practice/
204                 } else if (c.startsWith("RCPT TO:")) {
205                     // some clients are broken and put RCPT first; we will tolerate this
206                     command = command.substring(8).trim();
207                     if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
208                     Address addr = new Address(command);
209                     if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
210                         conn.println("250 you are connected locally, so I will let you send");
211                         to.addElement(addr);
212                         if (!whitelist.isWhitelisted(addr))
213                             whitelist.addWhitelist(addr);
214                     } else if (authenticatedAs!=null) {
215                         conn.println("250 you are authenticated as "+authenticatedAs+", so I will let you send");
216                         to.addElement(addr);
217                         if (!whitelist.isWhitelisted(addr))
218                             whitelist.addWhitelist(addr);
219                     } else if (addr.isLocal()) {
220                         if (to.size() > 3) {
221                             conn.println("536 sorry, limit on 3 RCPT TO's per DATA");
222                         } else {
223                             // FEATURE: should check the address further and give 550 if undeliverable
224                             conn.println("250 " + addr + " is on this machine; I will deliver it");
225                             to.addElement(addr);
226                         }
227                     } else {
228                         conn.println("535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
229                         Log.warn("","535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
230                         failedRcptCount++;
231                         if (failedRcptCount > 3) {
232                             conn.close();
233                             return;
234                         }
235                     }
236                     conn.flush();
237                 } else if (c.startsWith("DATA")) {
238                     //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
239                     if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
240                     if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress() && authenticatedAs==null) {
241                         long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
242                         if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
243                             graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"",  System.currentTimeMillis());
244                             conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
245                             Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
246                             conn.flush();
247                             continue;
248                         } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
249                             graylist.addWhitelist(conn.getRemoteAddress());
250                             conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
251                             Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
252                         } else {
253                             conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
254                             conn.flush();
255                             Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
256                             continue;
257                         }
258                     } else {
259                         conn.println("354 Enter message, ending with \".\" on a line by itself");
260                     }
261                     conn.flush();
262                     try {
263                         // FIXME: deal with messages larger than memory here?
264                         StringBuffer buf = new StringBuffer();
265                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
266                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
267                         buf.append("          for ");
268                         // FIXME: this is leaking BCC addrs
269                         // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
270                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
271
272                         // FIXME: some sort of stream transformer here?
273                         while(true) {
274                             String s = conn.readln();
275                             if (s == null) throw new RuntimeException("connection closed");
276                             if (s.equals(".")) break;
277                             if (s.startsWith(".")) s = s.substring(1);
278                             buf.append(s + "\r\n");
279                             if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE && (from+"").indexOf("paperless")==-1) {
280                                 Log.error("**"+conn.getRemoteAddress()+"**",
281                                           "sorry, this mail server only accepts messages of less than " +
282                                           ByteSize.toString(MAX_MESSAGE_SIZE));
283                                 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
284                                                                   ByteSize.toString(MAX_MESSAGE_SIZE));
285                             }
286                         }
287                         String message = buf.toString();
288                         Message m = null;
289                         for(int i=0; i<to.size(); i++)
290                             enqueue(m = Message.newMessage(Fountain.Util.create(message)).withEnvelope(from, (Address)to.elementAt(i)));
291                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
292                         conn.println("250 message accepted");
293                         conn.flush();
294                         from = null; to = new Vector();
295                     } catch (MailException.Malformed mfe) {    conn.println("501 " + mfe.toString());
296                     } catch (MailException.MailboxFull mbf) {  conn.println("452 " + mbf);
297                     } catch (Script.Later.LaterException le) { conn.println("453 try again later");
298                     } catch (Script.Reject.RejectException re) {
299                         Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n   " + re.m.summary());
300                         conn.println("501 " + re.reason);
301                     }
302                 } else                    { conn.println("500 unrecognized command"); }                    
303             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
304         }
305     }
306
307
308     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
309
310     public static class Outgoing extends Thread {
311
312         private static final HashMap deadHosts = new HashMap();
313         public static void enqueue(Message m) throws IOException {
314             if (m == null) { Log.warn(Outgoing.class, "attempted to enqueue(null)"); return; }
315             String traces = m.headers.get("Received");
316             if (traces!=null) {
317                 int lines = 0;
318                 for(int i=0; i<traces.length(); i++)
319                     if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
320                         lines++;
321                 if (lines > 100) { // required by rfc
322                     Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
323                     return;
324                 }
325             }
326             synchronized(Outgoing.class) {
327                 spool.insert(m, Mailbox.Flag.defaultFlags);
328                 Outgoing.class.notifyAll();
329             }
330         }
331
332         public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
333         public static boolean attempt(Message m, boolean noBounces) throws IOException {
334             if (m.envelopeTo == null) {
335                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
336                 return false;
337             }
338             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
339             if (mx.length == 0) {
340                 if (!noBounces) {
341                     enqueue(m.bounce("could not resolve " + m.envelopeTo.host));
342                     return true;
343                 } else {
344                     Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
345                     return false;
346                 }
347             }
348             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
349                 if (!noBounces) {
350                     enqueue(m.bounce("could not send for 5 days"));
351                     return true;
352                 } else {
353                     Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
354                     return false;
355                 }
356             }
357             for(int i=0; i<mx.length; i++) {
358                 //if (deadHosts.contains(mx[i])) continue;
359                 if (attempt(m, mx[i])) return true;
360             }
361             return false;
362         }
363
364         private static void check(String s, Connection conn) {
365             if (s==null) return;
366             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
367             //if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
368             if (!s.startsWith("2")&&!s.startsWith("3")) throw new SMTPException(s);
369         }
370         private static boolean attempt(final Message m, final InetAddress mx) {
371             boolean accepted = false;
372             Connection conn = null;
373             try {
374                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
375                 InetAddress localAddress = conn.getSocket().getLocalAddress();
376                 String reverse = DNSUtil.reverseLookup(localAddress);
377                 Log.info(SMTP.Outgoing.class,
378                          "outbound connection to " + mx + " uses " + localAddress + " [reverse: " + reverse + "]");
379                 InetAddress relookup = InetAddress.getByName(reverse);
380                 if (!relookup.equals(localAddress))
381                     Log.error(SMTP.Outgoing.class,
382                               "Warning: local machine fails forward-confirmed-reverse; " +
383                               reverse + " resolves to " + localAddress);
384                 conn.setNewline("\r\n");
385                 conn.setTimeout(60 * 1000);
386                 check(conn.readln(), conn);  // banner
387                 try {
388                     conn.println("EHLO " + reverse);
389                     check(conn.readln(), conn);
390                 } catch (SMTPException smtpe) {
391                     conn.println("HELO " + reverse);
392                     check(conn.readln(), conn);
393                 }
394                 String envelopeFrom = m.envelopeFrom==null ? "" : m.envelopeFrom.toString();
395                 conn.println("MAIL FROM:<" + envelopeFrom +">");            check(conn.readln(), conn);
396                 conn.println("RCPT TO:<"   + m.envelopeTo.toString()+">");  check(conn.readln(), conn);
397                 conn.println("DATA");                                       check(conn.readln(), conn);
398
399                 Headers head = new Headers(m.headers,
400                                            new String[] {
401                                                "return-path", null,
402                                                "bcc", null
403                                            });
404                 Stream stream = head.getStream();
405                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
406                     if (s.startsWith(".")) conn.print(".");
407                     conn.println(s);
408                 }
409                 conn.println("");
410                 stream = m.getBody().getStream();
411                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
412                     if (s.startsWith(".")) conn.print(".");
413                     conn.println(s);
414                 }
415                 conn.println(".");
416                 String resp = conn.readln();
417                 if (resp == null)
418                     throw new SMTPException("server " + mx + " closed connection without accepting message");
419                 check(resp, conn);
420                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
421                 accepted = true;
422                 conn.close();
423             } catch (SMTPException e) {
424                 if (accepted) return true;
425                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
426                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
427                 Log.warn(SMTP.Outgoing.class, e);
428                 /*
429                   // FIXME: we should not be bouncing here!
430                 if (e.code >= 500 && e.code <= 599) {
431                     try {
432                         attempt(m.bounce("unable to deliver: " + e), true);
433                     } catch (Exception ex) {
434                         Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
435                         Log.error(SMTP.Outgoing.class, ex);
436                     }
437                     return true;
438                 }
439                 */
440                 return false;
441             } catch (Exception e) {
442                 if (accepted) return true;
443                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
444                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
445                 Log.warn(SMTP.Outgoing.class, e);
446                 //if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
447                 return false;
448             } finally {
449                 if (conn != null) conn.close();
450             }
451             return accepted;
452         }
453
454         private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
455         private static int serials = 1;
456         private int serial = serials++;
457         private Mailbox.Iterator it;
458
459         private static Map<String,Long> nextTry = Collections.synchronizedMap(new HashMap<String,Long>());
460
461         public Outgoing() {
462             synchronized(Outgoing.class) {
463                 threads.add(this);
464             }
465         }
466
467         public void wake() {
468             int count = spool.count(Query.all());
469             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
470             try {
471                 while(true) {
472                     boolean good = false;
473                     synchronized(Outgoing.class) {
474                         it = spool.iterator();
475                         OUTER: for(; it.next(); ) {
476                             for(Outgoing o : threads)
477                                 if (o!=this && o.it != null && o.it.uid()==it.uid())
478                                     continue OUTER;
479                             good = true;
480                             break;
481                         }
482                     }
483                     if (!good) break;
484                     try {
485                         String messageid = it.cur().messageid;
486                         if (nextTry.get(messageid) == null || System.currentTimeMillis() > nextTry.get(messageid)) {
487                             boolean ok = attempt(it.cur());
488                             if (ok) it.delete();
489                             else nextTry.put(messageid, System.currentTimeMillis() + RETRY_TIME);
490                         }
491                     } catch (Exception e) {
492                         Log.error(SMTP.Outgoing.class, e);
493                     }
494                     Log.info(this, "sleeping for 3s...");
495                     Thread.sleep(3000);
496                 }
497             } catch (Exception e) {
498                 //if (e instanceof InterruptedException) throw e;
499                 Log.error(SMTP.Outgoing.class, e);
500             }
501             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
502             it = null;
503         }
504
505         public void run() {
506             try {
507                 while(true) {
508                     Log.setThreadAnnotation("[outgoing #"+serial+"] ");
509                     wake();
510                     Thread.sleep(1000);
511                     synchronized(Outgoing.class) {
512                         Outgoing.class.wait(5 * 60 * 1000);
513                     }
514                 }
515             } catch (InterruptedException e) { Log.warn(this, e); }
516         }
517     }
518
519     public static InetAddress[] getMailExchangerIPs(String hostName) {
520         InetAddress[] ret;
521         try {
522             Hashtable env = new Hashtable();
523             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
524             DirContext ictx = new InitialDirContext(env);
525             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
526             Attribute attr = attrs.get("MX");
527             if (attr == null) {
528                 ret = new InetAddress[1];
529                 try {
530                     ret[0] = InetAddress.getByName(hostName);
531                     if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
532                     return ret;
533                 } catch (UnknownHostException uhe) {
534                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
535                     return new InetAddress[0];
536                 }
537             } else {
538                 ret = new InetAddress[attr.size()];
539                 NamingEnumeration ne = attr.getAll();
540                 for(int i=0; ne.hasMore();) {
541                     String mx = (String)ne.next();
542                     // FIXME we should be sorting here
543                     mx = mx.substring(mx.indexOf(" ") + 1);
544                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
545                     InetAddress ia = InetAddress.getByName(mx);
546                     if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
547                     ret[i++] = ia;
548                 }
549             }
550         } catch (Exception e) {
551             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
552             Log.warn(SMTP.class, e);
553             return new InetAddress[0];
554         }
555         return ret;
556     }
557 }