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