mail overhaul
[org.ibex.mail.git] / src / org / ibex / mail / protocol / SMTP.java
1 package org.ibex.mail.protocol;
2 import org.ibex.mail.*;
3 import org.ibex.mail.target.*;
4 import org.ibex.util.*;
5 import org.ibex.io.*;
6 import org.ibex.net.*;
7 import java.net.*;
8 import java.io.*;
9 import java.util.*;
10 import java.text.*;
11 import javax.naming.*;
12 import javax.naming.directory.*;
13
14 // FEATURE: exponential backoff on retry time?
15 public class SMTP {
16
17     private static final Mailbox spool =
18         FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
19
20     static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
21
22     // Server //////////////////////////////////////////////////////////////////////////////
23
24     public static class Server implements Worker {
25         public void handleRequest(Connection conn) {
26             conn.setTimeout(5 * 60 * 1000);
27             conn.out.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
28             Address from = null;
29             Vector to = new Vector();
30             for(String command = conn.in.readln(); ; command = conn.in.readln()) {
31                 String c = command.toUpperCase();
32                 if (c.startsWith("HELO"))        { conn.out.println("250 HELO " + conn.vhost); from = null; to = new Vector();
33                 } else if (c.startsWith("EHLO")) { conn.out.println("250");                    from = null; to = new Vector();
34                 } else if (c.startsWith("RSET")) { conn.out.println("250 reset ok");           from = null; to = new Vector();
35                 } else if (c.startsWith("HELP")) { conn.out.println("214 you are beyond help.  see a trained professional.");
36                 } else if (c.startsWith("VRFY")) { conn.out.println("252 We don't VRFY; proceed anyway");
37                 } else if (c.startsWith("EXPN")) { conn.out.println("550 EXPN not available");
38                 } else if (c.startsWith("NOOP")) { conn.out.println("250 OK");
39                 } else if (c.startsWith("QUIT")) { conn.out.println("221 " + conn.vhost + " closing connection"); return;
40                 } else if (c.startsWith("MAIL FROM:")) {
41                     conn.out.println("250 " + (from = new Address(command.substring(10).trim())) + " is syntactically correct");
42                 } else if (c.startsWith("RCPT TO:")) {
43                     if (from == null) { conn.out.println("503 MAIL FROM must precede RCPT TO"); continue; }
44                     command = command.substring(8).trim();
45                     if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
46                     Address addr = new Address(command);
47                     InetAddress[] mx = getMailExchangerIPs(addr.host);
48                     to.addElement(addr);
49                     if (conn.getRemoteAddress().isLoopbackAddress()) {
50                         conn.out.println("250 you are connected locally, so I will let you send");
51                     } else {
52                         boolean good = false;
53                         for(int i=0; !good && i<mx.length; i++) {
54                             try {
55                                 if (NetworkInterface.getByInetAddress(mx[i]) != null) good = true;
56                             } catch (Exception e) { /* DELIBERATE */ }
57                         }
58                         if (!good) { conn.out.println("551 sorry, " + addr + " is not on this machine"); return; }
59                         conn.out.println("250 " + addr + " is on this machine; I will deliver it");
60                     }
61                 } else if (c.startsWith("DATA")) {
62                     if (from == null) { conn.out.println("503 MAIL FROM command must precede DATA"); continue; }
63                     if (to == null) { conn.out.println("503 RCPT TO command must precede DATA"); continue; }
64                     conn.out.println("354 Enter message, ending with \".\" on a line by itself");
65                     try {
66                         StringBuffer buf = new StringBuffer();
67                         for(String s = conn.in.readln(); ; s = conn.in.readln()) {
68                             if (s == null) throw new RuntimeException("connection closed");
69                             if (s.equals(".")) break;
70                             if (s.startsWith(".")) s = s.substring(1);
71                             buf.append(s);
72                         }
73                         String body = buf.toString();
74                         for(int i=0; i<to.size(); i++) {
75                             Message m = new Message(from, (Address)to.elementAt(i), new Stream(body));
76                             Target.root.accept(m);
77                         }
78                         conn.out.println("250 message accepted");
79                         from = null; to = new Vector();
80                     } catch (MailException.Malformed mfe) {   conn.out.println("501 " + mfe.toString());
81                     } catch (MailException.MailboxFull mbf) { conn.out.println("452 " + mbf);
82                     } catch (IOException ioe) {               conn.out.println("554 " + ioe.toString());
83                     }
84                 } else                           { conn.out.println("500 unrecognized command"); }                    
85             }
86         }
87     }
88
89
90     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
91
92     public static class Outgoing {
93         private static final HashSet deadHosts = new HashSet();
94         public static void send(Message m) throws IOException {
95             if (m.traces.length >= 100)
96                 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
97             else synchronized(Outgoing.class) {
98                 spool.add(m);
99                 Outgoing.class.notify();
100             }
101         }
102
103         private static boolean attempt(Message m) throws IOException {
104             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
105             if (mx.length == 0) {
106                 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
107                 send(m.bounce("could not resolve " + m.envelopeTo.host));
108                 return true;
109             }
110             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
111                 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
112                 send(m.bounce("could not send for 5 days"));
113                 return true;
114             }
115             for(int i=0; i<mx.length; i++) {
116                 if (deadHosts.contains(mx[i])) continue;
117                 if (attempt(m, mx[i])) { return true; }
118             }
119             return false;
120         }
121
122         private static void check(String s) { if (s.startsWith("4")||s.startsWith("5")) throw new MailException(s); }
123         private static boolean attempt(final Message m, final InetAddress mx) {
124             boolean accepted = false;
125             try {
126                 Log.info(SMTP.Outgoing.class, "connecting...");
127                 Connection conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
128                 Log.info(SMTP.Outgoing.class, "connected");
129                 check(conn.in.readln());  // banner
130                 conn.out.println("HELO " + conn.vhost);            check(conn.in.readln());
131                 conn.out.println("MAIL FROM: " + m.envelopeFrom);  check(conn.in.readln());
132                 conn.out.println("RCPT TO: " + m.envelopeTo);      check(conn.in.readln());
133                 conn.out.println("DATA");                          check(conn.in.readln());
134                 conn.out.println(m.body);
135                 conn.out.println(".");
136                 check(conn.in.readln());
137                 Log.info(SMTP.Outgoing.class, "message accepted by " + mx);
138                 accepted = true;
139                 conn.close();
140             } catch (Exception e) {
141                 if (accepted) return true;
142                 Log.warn(SMTP.Outgoing.class, "unable to send; error=" + e);
143                 Log.warn(SMTP.Outgoing.class, e);
144                 return false;
145             } finally { Log.setThreadAnnotation("[outgoing smtp] "); }
146             return accepted;
147         }
148
149         static void runq() {
150             try {
151                 Log.setThreadAnnotation("[outgoing smtp] ");
152                 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
153                 while(true) {
154                     for(Mailbox.Iterator it = spool.iterator(); it.next(); )
155                         try                   { if (attempt(it.cur())) it.delete(); }
156                         catch (IOException e) { Log.error(SMTP.Outgoing.class, e); }
157                     synchronized(Outgoing.class) {
158                         Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
159                         Outgoing.class.wait(10 * 60 * 1000);
160                         deadHosts.clear();
161                         Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
162                     }
163                 }
164             } catch (Exception e) { Log.error(SMTP.Outgoing.class, e); }
165         }
166     }
167
168     public static InetAddress[] getMailExchangerIPs(String hostName) {
169         InetAddress[] ret;
170         try {
171             Hashtable env = new Hashtable();
172             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
173             DirContext ictx = new InitialDirContext(env);
174             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
175             Attribute attr = attrs.get("MX");
176             if (attr == null) {
177                 ret = new InetAddress[1];
178                 try {
179                     ret[0] = InetAddress.getByName(hostName);
180                     return ret;
181                 } catch (UnknownHostException uhe) {
182                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
183                     return new InetAddress[0];
184                 }
185             } else {
186                 ret = new InetAddress[attr.size()];
187                 NamingEnumeration ne = attr.getAll();
188                 for(int i=0; ne.hasMore(); i++) {
189                     String mx = (String)ne.next();
190                     // FIXME we should be sorting here
191                     mx = mx.substring(mx.indexOf(" ") + 1);
192                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
193                     ret[i] = InetAddress.getByName(mx);
194                 }
195             }
196         } catch (Exception e) {
197             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
198             Log.warn(SMTP.class, e);
199             return new InetAddress[0];
200         }
201         return ret;
202     }
203 }