more fixups to MailingList
[org.ibex.mail.git] / src / org / ibex / mail / protocol / SMTP.java
index 9ebb15a..af39827 100644 (file)
@@ -1,10 +1,12 @@
+// 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.jinetd.Worker;
 import org.ibex.util.*;
 import org.ibex.io.*;
-import org.ibex.net.*;
 import java.net.*;
 import java.io.*;
 import java.util.*;
@@ -12,53 +14,94 @@ import java.text.*;
 import javax.naming.*;
 import javax.naming.directory.*;
 
+// FIXME: bounce messages (must go to return-path unless empty, in which case do not send
+// FIXME: if more than 100 "Received" lines, must drop message
+// FEATURE: infer messageid, date, if not present (?)
+// 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: exponential backoff on retry time?
+// 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");
     private static final Mailbox spool =
         FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
 
     static { new Thread() { public void run() { Outgoing.runq(); } }.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) {
+            code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
+            message = s.substring(s.indexOf(' ')+1);
+        }
+        public String toString() { return "SMTP " + code + ": " + message; }
+        public String getMessage() { return toString(); }
+    }
+
     // Server //////////////////////////////////////////////////////////////////////////////
 
-    public static class Server implements Worker {
+    public static class Server {
         public void handleRequest(Connection conn) {
-            Log.error(this, "accepted...");
             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;
                 String c = command.toUpperCase();
-                if (c.startsWith("HELO"))        { conn.println("250 HELO " + conn.vhost); from = null; to = new Vector();
-                } else if (c.startsWith("EHLO")) { conn.println("250");                    from = null; to = new Vector();
+                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");
+                    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("252 We don't VRFY; proceed anyway");
-                } else if (c.startsWith("EXPN")) { conn.println("550 EXPN not available");
+                } 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:")) {
-                    conn.println("250 " + (from = new Address(command.substring(10).trim())) + " is syntactically correct");
+                    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:")) {
-                    if (from == null) { conn.println("503 MAIL FROM must precede RCPT TO"); continue; }
+                    // 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);
-                    if (addr.isLocal()) conn.println("250 " + addr + " is on this machine; I will deliver it");
-                    else if (conn.getRemoteAddress().isLoopbackAddress())
+                    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");
+                    } else if (conn.getRemoteAddress().isLoopbackAddress())
                         conn.println("250 you are connected locally, so I will let you send");
                     else { conn.println("551 sorry, " + addr + " is not on this machine"); }
                     to.addElement(addr);
                 } else if (c.startsWith("DATA")) {
-                    if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
+                    //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
                     if (to == null) { conn.println("503 RCPT TO command must precede DATA"); continue; }
                     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 "); 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");
@@ -69,9 +112,8 @@ public class SMTP {
                         String body = buf.toString();
                         Message m = null;
                         for(int i=0; i<to.size(); i++) {
-                           m = new Message(from, (Address)to.elementAt(i), new Stream(body));
-                            if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
-                            else                         Target.root.accept(m);
+                           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");
@@ -79,10 +121,15 @@ public class SMTP {
                         from = null; to = new Vector();
                     } catch (MailException.Malformed mfe) {   conn.println("501 " + mfe.toString());
                     } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
-                    } catch (IOException ioe) {               conn.println("554 " + ioe.toString());
+                    } catch (Later.LaterException le) {       conn.println("453 try again later");
+                    } catch (IOException ioe) {               
+                        //conn.println("554 " + ioe.toString());
+                        Log.error(this, ioe);
+                        conn.close();
+                        return;
                     }
-                } else                           { conn.println("500 unrecognized command"); }                    
-            } catch (Message.Malformed e) { conn.println("501 " + e.toString()); /* FIXME could be wrong code */ }
+                } else                    { conn.println("500 unrecognized command"); }                    
+            } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
         }
     }
 
@@ -93,9 +140,12 @@ public class SMTP {
 
         private static final HashSet deadHosts = new HashSet();
         public static void accept(Message m) throws IOException {
-            Log.info(SMTP.class, "queued:\n" + m.summary());
+            if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
+            //Log.info(SMTP.class, "queued: " + m.summary());
+            /*
             if (m.traces.length >= 100)
                 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
+            */
             else synchronized(Outgoing.class) {
                 spool.add(m);
                 Outgoing.class.notify();
@@ -103,6 +153,10 @@ public class SMTP {
         }
 
         public static boolean attempt(Message m) 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(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
@@ -122,31 +176,53 @@ public class SMTP {
         }
 
         private static void check(String s, Connection conn) {
-            while (s.charAt(3) == '-') s = conn.readln();
-            if (s.startsWith("4")||s.startsWith("5")) throw new MailException(s);
+            while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
+            if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
         }
         private static boolean attempt(final Message m, final InetAddress mx) {
             boolean accepted = false;
             Connection conn = null;
             try {
-                Log.info(SMTP.Outgoing.class, "connecting to " + mx + "...");
+                Log.note("connecting to " + mx + "...");
                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
+                conn.setNewline("\r\n");
                 conn.setTimeout(60 * 1000);
-                Log.info(SMTP.Outgoing.class, "connected");
+                Log.note("    connected");
                 check(conn.readln(), conn);  // banner
-                conn.println("HELO " + conn.vhost);            check(conn.readln(), conn);
-                conn.println("MAIL FROM:<" + m.envelopeFrom.user + "@" + m.envelopeFrom.host+">");  check(conn.readln(), conn);
+                try {
+                    conn.println("EHLO " + conn.vhost);
+                    check(conn.readln(), conn);
+                } catch (SMTPException smtpe) {
+                    conn.println("HELO " + conn.vhost);
+                    check(conn.readln(), conn);
+                }
+                if (m.envelopeFrom==null) {
+                    conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
+                } else {
+                    conn.println("MAIL FROM:<" + m.envelopeFrom.user + "@" + m.envelopeFrom.host+">");  check(conn.readln(), conn);
+                }
                 conn.println("RCPT TO:<"   + m.envelopeTo.user + "@" + m.envelopeTo.host+">");      check(conn.readln(), conn);
                 conn.println("DATA");                          check(conn.readln(), conn);
-                conn.println(m.toString());
+                Stream stream = m.getStream();
+                boolean inheaders = true;
+                while(true) {
+                    String s = stream.readln();
+                    if (s == null) break;
+                    if (s.length() == 0) inheaders = false;
+                    // quash Return-Path; required by RFC2822
+                    if (inheaders && s.toLowerCase().startsWith("Return-Path:")) continue;
+                    if (s.startsWith(".")) conn.print(".");
+                    conn.println(s);
+                }
                 conn.println(".");
                 check(conn.readln(), conn);
-                Log.info(SMTP.Outgoing.class, "success: message accepted by " + mx);
+                Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary());
                 accepted = true;
                 conn.close();
             } catch (Exception e) {
                 if (accepted) return true;
-                Log.warn(SMTP.Outgoing.class, "unable to send; error=" + e);
+                Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
+                Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
                 Log.warn(SMTP.Outgoing.class, e);
                 return false;
             } finally {
@@ -160,18 +236,28 @@ public class SMTP {
                 Log.setThreadAnnotation("[outgoing smtp] ");
                 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
                 while(true) {
+                    if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
                     for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
-                        try                   { if (attempt(it.cur())) it.delete(); }
-                        catch (Exception e)   { Log.error(SMTP.Outgoing.class, e); }
+                        try {
+                            if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
+                            if (attempt(it.cur())) it.delete();
+                        } catch (Exception e)   {
+                            if (e instanceof InterruptedException) throw e;
+                            Log.error(SMTP.Outgoing.class, e);
+                        }
                     }
                     synchronized(Outgoing.class) {
+                        if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
                         Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
                         Outgoing.class.wait(5 * 60 * 1000);
                         deadHosts.clear();
                         Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
                     }
                 }
-            } catch (Exception e) { Log.error(SMTP.Outgoing.class, e); }
+            } catch (Exception e) {
+                Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e);
+                Log.error(SMTP.Outgoing.class, e);
+            }
         }
     }