change num() to imapNumber() and nntpNumber(), add comments about semantics
[org.ibex.mail.git] / src / org / ibex / mail / protocol / SMTP.java
index f996c09..af62e21 100644 (file)
@@ -1,7 +1,13 @@
+// Copyright 2000-2005 the Contributors, as shown in the revision logs.
+// Licensed under the Apache Public Source License 2.0 ("the License").
+// You may not use this file except in compliance with the License.
+
 package org.ibex.mail.protocol;
 import org.ibex.mail.*;
 import org.ibex.mail.target.*;
 import org.ibex.util.*;
+import org.ibex.net.*;
+import org.ibex.io.*;
 import java.net.*;
 import java.io.*;
 import java.util.*;
@@ -9,281 +15,386 @@ import java.text.*;
 import javax.naming.*;
 import javax.naming.directory.*;
 
-public class SMTP extends MessageProtocol {
+// FIXME: logging: current logging sucks
+// FIXME: loop prevention
+// FIXME: probably need some throttling on outbound mail
+
+// FEATURE: infer messageid, date, if not present (?)
+// FEATURE: exponential backoff on retry time?
+// FEATURE: RFC2822, section 4.5.1: special "postmaster" address
+// FEATURE: RFC2822, section 4.5.4.1: retry strategies
+// FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
+// FEATURE: RFC2822, end of 4.1.2: backslashes in headers
+public class SMTP {
+
+    public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
+    public static final int numOutgoingThreads = 5;
+
+    public static final int GRAYLIST_MINWAIT =  1000 * 60 * 60;           // one hour
+    public static final int GRAYLIST_MAXWAIT =  1000 * 60 * 60 * 24 * 5;  // five days
+
+    public static final Graylist graylist =
+        new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite");
+
+    public static final Whitelist whitelist =
+        new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite");
+
+    public static final int MAX_MESSAGE_SIZE =
+        Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
+
+    private static final Mailbox spool =
+        FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
+
+    static {
+        for(int i=0; i<numOutgoingThreads; i++)
+            new Outgoing().start();
+    }
+
+    public static void accept(Message m) throws IOException {
+        if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
+        else                         Target.root.accept(m);
+    }
+
+    public static class SMTPException extends MailException {
+        int code;
+        String message;
+        public SMTPException(String s) {
+            try {
+                code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
+                message = s.substring(s.indexOf(' ')+1);
+            } catch (NumberFormatException nfe) {
+                code = -1;
+                message = s;
+            }
+        }
+        public String toString() { return "SMTP " + code + ": " + message; }
+        public String getMessage() { return toString(); }
+    }
+
+    // Server //////////////////////////////////////////////////////////////////////////////
 
-    static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
-    public static String convdir = null;
-    public static void main(String[] s) throws Exception {
-        String logto = System.getProperty("ibex.mail.root", File.separatorChar + "var" + File.separatorChar + "org.ibex.mail");
-        logto += File.separatorChar + "log";
-        Log.file(logto);
-        convdir = System.getProperty("ibex.mail.root", File.separatorChar + "var" + File.separatorChar + "org.ibex.mail");
-        convdir += File.separatorChar + "conversation";
-        new File(convdir).mkdirs();
-        SMTP smtp = new SMTP();
-        int port = Integer.parseInt(System.getProperty("ibex.mail.port", "25"));
-        Log.info(SMTP.class, "binding to port " + port + "...");
-        ServerSocket ss = new ServerSocket(port);
-        Log.info(SMTP.class, "listening for connections...");
-        while(true) {
-            final Socket sock = ss.accept();
-            new Thread() { public void run() { smtp.handle(sock); } }.start();
+    public static class Server {
+        public void handleRequest(Connection conn) throws IOException {
+            conn.setTimeout(5 * 60 * 1000);
+            conn.setNewline("\r\n");
+            conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
+            Address from = null;
+            Vector to = new Vector();
+            boolean ehlo = false;
+            String remotehost = null;
+            for(String command = conn.readln(); ; command = conn.readln()) try {
+                if (command == null) return;
+                //Log.warn("**"+conn.getRemoteAddress()+"**", command);
+                String c = command.toUpperCase();
+                if (c.startsWith("HELO"))        {
+                    remotehost = c.substring(5).trim();
+                    conn.println("250 HELO " + conn.vhost);
+                    from = null; to = new Vector();
+                } else if (c.startsWith("EHLO")) {
+                    remotehost = c.substring(5).trim();
+                    conn.println("250 "+conn.vhost+" greets " + remotehost);
+                    ehlo = true;     
+                    from = null; to = new Vector();
+                } else if (c.startsWith("RSET")) { conn.println("250 reset ok");           from = null; to = new Vector();
+                } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help.  see a trained professional.");
+                } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
+                } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
+                } else if (c.startsWith("NOOP")) { conn.println("250 OK");
+                } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
+                } else if (c.startsWith("MAIL FROM:")) {
+                    command = command.substring(10).trim();
+                    from = command.equals("<>") ? null : new Address(command);
+                    conn.println("250 " + from + " is syntactically correct");
+                } else if (c.startsWith("RCPT TO:")) {
+                    // some clients are broken and put RCPT first; we will tolerate this
+                    command = command.substring(8).trim();
+                    if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
+                    Address addr = new Address(command);
+                    /*
+                    Log.warn("**"+conn.getRemoteAddress()+"**",
+                             "addr.isLocal(): " + addr.isLocal() + "\n" +
+                             "conn.getRemoteAddress().isLoopbackAddress(): " + conn.getRemoteAddress().isLoopbackAddress() + "\n" +
+                             "johnw: " + (from!=null&&from.toString().indexOf("johnw")!=-1) + "\n"
+                             );
+                    */
+                    if (addr.isLocal()) {
+                        // FEATURE: should check the address further and give 550 if undeliverable
+                        conn.println("250 " + addr + " is on this machine; I will deliver it");
+                        to.addElement(addr);
+                    } else if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
+                        conn.println("250 you are connected locally, so I will let you send");
+                        to.addElement(addr);
+                    } else {
+                        conn.println("551 sorry, " + addr + " is not on this machine");
+                    }
+                    conn.flush();
+                } else if (c.startsWith("DATA")) {
+                    //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
+                    if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
+                    if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress()) {
+                        long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
+                        if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
+                            graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"",  System.currentTimeMillis());
+                            conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
+                            Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
+                            conn.flush();
+                            continue;
+                        } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
+                            graylist.addWhitelist(conn.getRemoteAddress());
+                            conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
+                            Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
+                        } else {
+                            conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
+                            conn.flush();
+                            Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
+                            continue;
+                        }
+                    } else {
+                        conn.println("354 Enter message, ending with \".\" on a line by itself");
+                    }
+                    conn.flush();
+                    try {
+                        StringBuffer buf = new StringBuffer();
+                        buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
+                        buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
+                        buf.append("          for ");
+                        // FIXME: this is leaking BCC addrs
+                        // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
+                        buf.append("; " + dateFormat.format(new Date()) + "\r\n");
+                        while(true) {
+                            String s = conn.readln();
+                            if (s == null) throw new RuntimeException("connection closed");
+                            if (s.equals(".")) break;
+                            if (s.startsWith(".")) s = s.substring(1);
+                            buf.append(s + "\r\n");
+                            if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE) {
+                                Log.error("**"+conn.getRemoteAddress()+"**",
+                                          "sorry, this mail server only accepts messages of less than " +
+                                          ByteSize.toString(MAX_MESSAGE_SIZE));
+                                throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
+                                                                  ByteSize.toString(MAX_MESSAGE_SIZE));
+                            }
+                        }
+                        String body = buf.toString();
+                        Message m = null;
+                        for(int i=0; i<to.size(); i++) {
+                           m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
+                            accept(m);
+                       }
+                        if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
+                        conn.println("250 message accepted");
+                        conn.flush();
+                        from = null; to = new Vector();
+                    } catch (Reject.RejectException re) {
+                       Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n   " + re.m.summary());
+                       conn.println("501 " + re.reason);
+                    } catch (MailException.Malformed mfe) {   conn.println("501 " + mfe.toString());
+                    } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
+                    } catch (Later.LaterException le) {       conn.println("453 try again later");
+                    }
+                } else                    { conn.println("500 unrecognized command"); }                    
+            } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
         }
     }
 
-    //public SMTP() { setProtocolName("SMTP"); }
-    //public ServerRequest createRequest(Connection conn) { return new Listener((TcpConnection)conn); }
 
-    public void handle(Socket s) { new Listener(s, "megacz.com").handleRequest(); }
+    // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
 
-    //  FEATURE: exponential backoff on retry time?
-    public static class Outgoing {
-        private static final HashSet deadHosts = new HashSet();
-        private static final org.ibex.util.Queue queue = new org.ibex.util.Queue(100);
-        private static FileSystem store = FileSystem.root.slash("outgoing");
+    public static class Outgoing extends Thread {
 
-        public static void send(Message m) {
-            if (m.traces.length >= 100) {
-                Log.warn("Message with " + m.traces.length + " trace hops; silently dropping\n" + m.summary());
-                return;
+        private static final HashMap deadHosts = new HashMap();
+        public static void accept(Message m) throws IOException {
+            if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
+            String traces = m.headers.get("Received");
+            if (traces!=null) {
+                int lines = 0;
+                for(int i=0; i<traces.length(); i++)
+                    if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
+                        lines++;
+                if (lines > 100) { // required by rfc
+                    Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
+                    return;
+                }
             }
             synchronized(Outgoing.class) {
-                store.add(m);
-                queue.append(m);
-                Outgoing.class.notify();
+                spool.add(m);
+                Outgoing.class.notifyAll();
             }
         }
 
-        private static boolean attempt(Message m) {
+        public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
+        public static boolean attempt(Message m, boolean noBounces) throws IOException {
+            if (m.envelopeTo == null) {
+                Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
+                return false;
+            }
             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
             if (mx.length == 0) {
-                Log.warn("could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
-                send(m.bounce("could not resolve " + m.envelopeTo.host));
-                return true;
+               if (!noBounces) {
+                   accept(m.bounce("could not resolve " + m.envelopeTo.host));
+                   return true;
+               } else {
+                   Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
+                   return false;
+               }
             }
             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
-                Log.warn("could not send message after 5 days; bouncing it\n" + m.summary());
-                send(m.bounce("could not send for 5 days"));
-                return true;
+               if (!noBounces) {
+                   accept(m.bounce("could not send for 5 days"));
+                   return true;
+               } else {
+                   Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
+                   return false;
+               }
             }
             for(int i=0; i<mx.length; i++) {
-                if (deadHosts.contains(mx[i])) continue;
-                if (attempt(m, mx[i])) { queue.remove(m); return true; }
+                //if (deadHosts.contains(mx[i])) continue;
+                if (attempt(m, mx[i])) { return true; }
             }
             return false;
         }
 
-        private static boolean attempt(Message m, InetAddress mx) {
-            try {
-                String conversationId = getConversation();
-                PrintWriter logf = new PrintWriter(new OutputStreamWriter(new FileOutputStream(convdir+File.separatorChar+cid)));
-                Log.setThreadAnnotation("[outgoing smtp: " + mx + " / " + cid + "] ");
-                Log.info(SMTP.Outgoing.class, "connecting...");
-                Socket s = new Socket(mx, 25);
-                Log.info(SMTP.Outgoing.class, "connected");
-                LineReader  r = new LoggedLineReader(new InputStreamReader(conn.getInputStream()), logf);
-                PrintWriter w = new LoggedPrintWriter(new OutputStreamWriter(conn.getOutputStream()), logf);
-                                                                  check(r.readLine());  // banner
-                w.print("HELO " + vhost + "\r\n");                check(r.readLine());
-                w.print("MAIL FROM: " + m.envelopeFrom + "\r\n"); check(r.readLine());
-                w.print("RCPT TO: " + m.envelopeTo + "\r\n");     check(r.readLine());
-                w.print("DATA\r\n");                              check(r.readLine());
-                w.print(m.body);
-                w.print(".\r\n");
-                check(r.readLine());
-                Log.info(SMTP.Outgoing.class, "message accepted by " + mx);
-                m.delete();
-                s.close();
-                return true;
-            } catch (Exception e) {
-                Log.warn(SMTP.Outgoing.class, "unable to send; error=" + e);
-                Log.warn(SMTP.Outgoing.class, e);
-                return false;
-            } finally {
-                Log.setThreadAnnotation("[outgoing smtp] ");
-            }
-        }
-
-        static void runq() {
-            Log.setThreadAnnotation("[outgoing smtp] ");
-            int[] outgoing = store.list();
-            Log.info("outgoing thread started; " + outgoing.length + " messages to send");
-            for(int i=0; i<outgoing.length; i++) queue.append(store.get(outgoing[i]));
-            while(true) {
-                int num = queue.size();
-                for(int i=0; i<num; i++) {
-                    Message next = queue.remove(true);
-                    if (!attempt(next)) queue.append(next);
-                }
-                synchronized(Outgoing.class) {
-                    Log.info("outgoing thread going to sleep");
-                    Outgoing.class.wait(10 * 60 * 1000);
-                    deadHosts.clear();
-                    Log.info("outgoing thread woke up; " + queue.size() + " messages in queue");
-                }
-            }
+        private static void check(String s, Connection conn) {
+            if (s==null) return;
+            while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
+            if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
         }
-    }
-
-    private static String lastTime = null;
-    private static int lastCounter = 0;
-
-    private class Listener extends Incoming /*implements ServerRequest*/ {
-        Socket conn;
-        String vhost;
-        public void init() { }
-        public Listener(Socket conn, String vhost) { this.vhost = vhost; this.conn = conn; }
-
-        //TcpConnection conn;
-        //public Listener(TcpConnection conn) { this.conn = conn; conn.getSocket().setSoTimeout(5 * 60 * 1000); }
-        public boolean handleRequest() {
+        private static boolean attempt(final Message m, final InetAddress mx) {
+            boolean accepted = false;
+            Connection conn = null;
             try {
-                conn.setSoTimeout(5 * 60 * 1000);
-                StringBuffer logMessage = new StringBuffer();
-                String conversationId = getConversation();
-                Log.setThreadAnnotation("[conversation/" + conversationId + "] ");
-                InetSocketAddress remote = (InetSocketAddress)conn.getRemoteSocketAddress();
-                Log.info(this, "connection from " + remote.getHostName() + ":" + remote.getPort() +
-                         " (" + remote.getAddress() + ")");
-                PrintWriter logf =
-                    new PrintWriter(new OutputStreamWriter(new FileOutputStream(convdir + File.separatorChar + conversationId)));
+                Log.note("connecting to " + mx + "...");
+                conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
+                conn.setNewline("\r\n");
+                conn.setTimeout(60 * 1000);
+                Log.note("    connected");
+                check(conn.readln(), conn);  // banner
                 try {
-                    return handleRequest(new LoggedLineReader(new InputStreamReader(conn.getInputStream()), logf),
-                                         new LoggedPrintWriter(new OutputStreamWriter(conn.getOutputStream()), logf));
-                } catch(Throwable t) {
-                    Log.warn(this, t);
-                } finally {
-                    logf.close();
-                    Log.setThreadAnnotation("");
+                    conn.println("EHLO " + conn.vhost);
+                    check(conn.readln(), conn);
+                } catch (SMTPException smtpe) {
+                    conn.println("HELO " + conn.vhost);
+                    check(conn.readln(), conn);
                 }
-            } catch (Exception e) {
-                Log.error(this, e);
-            }
-            return false;
-        }
-        
-        static String getConversation() {
-            String time = new SimpleDateFormat("yy.MMM.dd-hh:mm:ss").format(new Date());
-            synchronized (SMTP.class) {
-                if (lastTime != null && lastTime.equals(time)) {
-                    time += "." + (++lastCounter);
+                if (m.envelopeFrom==null) {
+                    Log.warn("", "MAIL FROM:<>");
+                    conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
                 } else {
-                    lastTime = time;
+                    Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
+                    conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">");  check(conn.readln(), conn);
+                }
+                conn.println("RCPT TO:<"   + m.envelopeTo.toString()+">");      check(conn.readln(), conn);
+                conn.println("DATA");                          check(conn.readln(), conn);
+                Headers head = m.headers;
+                head = head.remove("return-path");
+                head = head.remove("bcc");
+                Stream stream = head.getStream();
+                for(String s = stream.readln(); s!=null; s=stream.readln()) {
+                    if (s.startsWith(".")) conn.print(".");
+                    conn.println(s);
+                }
+                conn.println("");
+                stream = m.getBody().getStream();
+                for(String s = stream.readln(); s!=null; s=stream.readln()) {
+                    if (s.startsWith(".")) conn.print(".");
+                    conn.println(s);
+                }
+                conn.println(".");
+                String resp = conn.readln();
+                if (resp == null)
+                    throw new SMTPException("server " + mx + " closed connection without accepting message");
+                check(resp, conn);
+                Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
+                accepted = true;
+                conn.close();
+            } catch (SMTPException e) {
+                if (accepted) return true;
+                Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
+                Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
+                Log.warn(SMTP.Outgoing.class, e);
+                if (e.code >= 500 && e.code <= 599) {
+                    try {
+                        attempt(m.bounce("unable to deliver: " + e), true);
+                    } catch (Exception ex) {
+                        Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
+                        Log.error(SMTP.Outgoing.class, ex);
+                    }
+                    return true;
                 }
+                return false;
+            } catch (Exception e) {
+                if (accepted) return true;
+                Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
+                Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
+                Log.warn(SMTP.Outgoing.class, e);
+                if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
+                return false;
+            } finally {
+                if (conn != null) conn.close();
             }
-            return time;
+            return accepted;
         }
 
-        private class LoggedLineReader extends LineReader {
-            PrintWriter log;
-            public LoggedLineReader(Reader r, PrintWriter log) { super(r); this.log = log; }
-            public String readLine() throws IOException {
-                String s = super.readLine();
-                if (s != null) { log.println("C: " + s); log.flush(); }
-                return s;
-            }
-        }
+        private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
+        private static int serials = 1;
+        private int serial = serials++;
+        private Mailbox.Iterator it;
 
-        private class LoggedPrintWriter extends PrintWriter {
-            PrintWriter log;
-            public LoggedPrintWriter(Writer w, PrintWriter log) { super(w); this.log = log; }
-            public void println(String s) {
-                log.println("S: " + s);
-                super.println(s);
-                flush();
+        public Outgoing() {
+            synchronized(Outgoing.class) {
+                threads.add(this);
             }
         }
 
-        public boolean handleRequest(LineReader rs, PrintWriter ws) throws IOException, MailException {
-            //ReadStream rs = conn.getReadStream();
-            //WriteStream ws = conn.getWriteStream();
-            //ws.setNewLineString("\r\n");
-            ws.println("220 " + vhost + " ESMTP " + this.getClass().getName());
-            Address from = null;
-            Vector to = new Vector();
-            while(true) {
-                String command = rs.readLine();
-                String c = command.toUpperCase();
-                if (c.startsWith("HELO")) {
-                    ws.println("250 HELO " + vhost);
-                    from = null;
-                    to = new Vector();
-
-                } else if (c.startsWith("EHLO")) {
-                    ws.println("250-" + vhost);
-                    ws.println("250-SIZE");
-                    ws.println("250 PIPELINING");
-                    from = null;
-                    to = new Vector();
-
-                } else if (c.startsWith("RSET")) {
-                    from = null;
-                    to = new Vector();
-                    ws.println("250 reset ok");
-
-                } else if (c.startsWith("MAIL FROM:")) {
-                    command = command.substring(10).trim();
-                    from = new Address(command);
-                    ws.println("250 " + from + " is syntactically correct");
-
-                } else if (c.startsWith("RCPT TO:")) {
-                    if (from == null) {
-                        ws.println("503 MAIL FROM must precede RCPT TO");
-                        continue;
-                    }
-                    command = command.substring(9).trim();
-                    if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
-                    Address addr = new Address(command);
-                    // FIXME: 551 = no, i won't forward that
-                    to.addElement(addr);
-                    ws.println("250 " + addr + " is syntactically correct");
-
-                } else if (c.startsWith("DATA")) {
-                    if (from == null) { ws.println("503 MAIL FROM command must precede DATA"); continue; }
-                    if (to == null) { ws.println("503 RCPT TO command must precede DATA"); continue; }
-                    ws.println("354 Enter message, ending with \".\" on a line by itself");
-                    StringBuffer data = new StringBuffer();
-                    // move this into the Message class
+        public void wake() {
+            int count = spool.count(Query.all());
+            Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
+            try {
+                while(true) {
                     boolean good = false;
-                    try {
-                        accept(new Message(new DotTerminatedLineReader(rs)));
-                    } catch (MailException.Malformed mfe) {
-                        ws.println("501 " + mfe.toString()); break;
-                    } catch (MailException.MailboxFull mbf) {
-                        ws.println("452 " + mbf);
-                    } catch (IOException ioe) {
-                        ws.println("554 " + ioe.toString()); break;
+                    synchronized(Outgoing.class) {
+                        it = spool.iterator();
+                        OUTER: for(; it.next(); ) {
+                            for(Outgoing o : threads)
+                                if (o!=this && o.it != null && o.it.uid()==it.uid())
+                                    continue OUTER;
+                            good = true;
+                            break;
+                        }
                     }
-                    ws.println("250 message accepted"); break;
-                    
-                } else if (c.startsWith("HELP")) { ws.println("214 you are beyond help.  see a trained professional.");
-                } else if (c.startsWith("VRFY")) { ws.println("252 We don't VRFY; proceed anyway");
-                } else if (c.startsWith("EXPN")) { ws.println("550 EXPN not available");
-                } else if (c.startsWith("NOOP")) { ws.println("250 OK");
-                } else if (c.startsWith("QUIT")) { ws.println("221 " + vhost + " closing connection"); break;
-                } else                           { ws.println("500 unrecognized command");
-                }                    
-            
+                    if (!good) break;
+                   try {
+                       if (attempt(it.cur())) it.delete();
+                   } catch (Exception e) {
+                       Log.error(SMTP.Outgoing.class, e);
+                   }
+                    Log.info(this, "sleeping for 3s...");
+                    Thread.sleep(3000);
+                }
+            } catch (Exception e) {
+                //if (e instanceof InterruptedException) throw e;
+                Log.error(SMTP.Outgoing.class, e);
             }
-            return false; // always tell resin to close the connection
+            Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
+            it = null;
         }
-    }
 
-    private static class DotTerminatedLineReader extends LineReader {
-        private final LineReader r;
-        private boolean done = false;
-        public DotTerminatedLineReader(LineReader r) { super(null); this.r = r; }
-        public String readLine() throws IOException {
-            if (done) return null;
-            String s = r.readLine();
-            if (s.equals(".")) { done = true; return null; }
-            if (s.startsWith(".")) return s.substring(1);
-            return s;
+        public void run() {
+            try {
+                while(true) {
+                    Log.setThreadAnnotation("[outgoing #"+serial+"] ");
+                    wake();
+                    Thread.sleep(1000);
+                    synchronized(Outgoing.class) {
+                        Outgoing.class.wait(5 * 60 * 1000);
+                    }
+                }
+            } catch (InterruptedException e) { Log.warn(this, e); }
         }
     }
 
-    public InetAddress[] getMailExchangerIPs(String domainName) {
-        InetAddress ret;
+    public static InetAddress[] getMailExchangerIPs(String hostName) {
+        InetAddress[] ret;
         try {
             Hashtable env = new Hashtable();
             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
@@ -293,24 +404,31 @@ public class SMTP extends MessageProtocol {
             if (attr == null) {
                 ret = new InetAddress[1];
                 try {
-                    ret[0] = InetAddress.getByName(domainName);
+                    ret[0] = InetAddress.getByName(hostName);
+                    if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
                     return ret;
                 } catch (UnknownHostException uhe) {
-                    Log.warn(SMTP.class, "no MX hosts or A record for " + domainName);
+                    Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
                     return new InetAddress[0];
                 }
             } else {
                 ret = new InetAddress[attr.size()];
                 NamingEnumeration ne = attr.getAll();
-                for(int i=0; ne.hasMore(); i++) ret[i] = (InetAddress)ne.next();
+                for(int i=0; ne.hasMore();) {
+                    String mx = (String)ne.next();
+                    // FIXME we should be sorting here
+                    mx = mx.substring(mx.indexOf(" ") + 1);
+                    if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
+                    InetAddress ia = InetAddress.getByName(mx);
+                    if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
+                    ret[i++] = ia;
+                }
             }
         } catch (Exception e) {
-            Log.warn(SMTP.class, "couldn't find MX host for " + domainName + " due to");
+            Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
             Log.warn(SMTP.class, e);
             return new InetAddress[0];
         }
         return ret;
     }
-
-
 }