better error handling
[org.ibex.mail.git] / src / org / ibex / mail / protocol / 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.protocol;
6 import org.ibex.mail.*;
7 import org.ibex.mail.target.*;
8 import org.ibex.util.*;
9 import org.ibex.net.*;
10 import org.ibex.io.*;
11 import java.net.*;
12 import java.io.*;
13 import java.util.*;
14 import java.text.*;
15 import javax.naming.*;
16 import javax.naming.directory.*;
17
18 // FIXME: bounce messages (must go to return-path unless empty, in which case do not send
19 // FIXME: if more than 100 "Received" lines, must drop message
20 // FEATURE: infer messageid, date, if not present (?)
21 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
22 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
23 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
24 // FEATURE: exponential backoff on retry time?
25 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
26 public class SMTP {
27
28     public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
29     private static final Mailbox spool =
30         FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
31
32     static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
33
34     public static void accept(Message m) throws IOException {
35         if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
36         else                         Target.root.accept(m);
37     }
38
39     public static class SMTPException extends MailException {
40         int code;
41         String message;
42         public SMTPException(String s) {
43             try {
44                 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
45                 message = s.substring(s.indexOf(' ')+1);
46             } catch (NumberFormatException nfe) {
47                 code = -1;
48                 message = s;
49             }
50         }
51         public String toString() { return "SMTP " + code + ": " + message; }
52         public String getMessage() { return toString(); }
53     }
54
55     // Server //////////////////////////////////////////////////////////////////////////////
56
57     public static class Server {
58         public void handleRequest(Connection conn) {
59             conn.setTimeout(5 * 60 * 1000);
60             conn.setNewline("\r\n");
61             conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
62             Address from = null;
63             Vector to = new Vector();
64             boolean ehlo = false;
65             String remotehost = null;
66             for(String command = conn.readln(); ; command = conn.readln()) try {
67                 if (command == null) return;
68                 String c = command.toUpperCase();
69                 if (c.startsWith("HELO"))        {
70                     remotehost = c.substring(5).trim();
71                     conn.println("250 HELO " + conn.vhost);
72                     from = null; to = new Vector();
73                 } else if (c.startsWith("EHLO")) {
74                     remotehost = c.substring(5).trim();
75                     conn.println("250");
76                     ehlo = true;     
77                     from = null; to = new Vector();
78                 } else if (c.startsWith("RSET")) { conn.println("250 reset ok");           from = null; to = new Vector();
79                 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help.  see a trained professional.");
80                 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
81                 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
82                 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
83                 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
84                 } else if (c.startsWith("MAIL FROM:")) {
85                     command = command.substring(10).trim();
86                     from = command.equals("<>") ? null : new Address(command);
87                     conn.println("250 " + from + " is syntactically correct");
88                 } else if (c.startsWith("RCPT TO:")) {
89                     // some clients are broken and put RCPT first; we will tolerate this
90                     command = command.substring(8).trim();
91                     if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
92                     Address addr = new Address(command);
93                     if (addr.isLocal()) {
94                         // FEATURE: should check the address further and give 550 if undeliverable
95                         conn.println("250 " + addr + " is on this machine; I will deliver it");
96                     } else if (conn.getRemoteAddress().isLoopbackAddress())
97                         conn.println("250 you are connected locally, so I will let you send");
98                         to.addElement(addr);
99                     } else {
100                         conn.println("551 sorry, " + addr + " is not on this machine");
101                     }
102                 } else if (c.startsWith("DATA")) {
103                     //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
104                     if (to == null) { conn.println("503 RCPT TO command must precede DATA"); continue; }
105                     conn.println("354 Enter message, ending with \".\" on a line by itself");
106                     conn.flush();
107                     try {
108                         StringBuffer buf = new StringBuffer();
109                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
110                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
111                         buf.append("          for ");
112                         // FIXME: this is leaking BCC addrs
113                         // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
114                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
115                         while(true) {
116                             String s = conn.readln();
117                             if (s == null) throw new RuntimeException("connection closed");
118                             if (s.equals(".")) break;
119                             if (s.startsWith(".")) s = s.substring(1);
120                             buf.append(s + "\r\n");
121                         }
122                         String body = buf.toString();
123                         Message m = null;
124                         for(int i=0; i<to.size(); i++) {
125                             m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
126                             accept(m);
127                         }
128                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
129                         conn.println("250 message accepted");
130                         conn.flush();
131                         from = null; to = new Vector();
132                     } catch (MailException.Malformed mfe) {   conn.println("501 " + mfe.toString());
133                     } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
134                     } catch (Later.LaterException le) {       conn.println("453 try again later");
135                     } catch (IOException ioe) {               
136                         //conn.println("554 " + ioe.toString());
137                         Log.error(this, ioe);
138                         conn.close();
139                         return;
140                     }
141                 } else                    { conn.println("500 unrecognized command"); }                    
142             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
143         }
144     }
145
146
147     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
148
149     public static class Outgoing {
150
151         private static final HashSet deadHosts = new HashSet();
152         public static void accept(Message m) throws IOException {
153             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
154             //Log.info(SMTP.class, "queued: " + m.summary());
155             /*
156             if (m.traces.length >= 100)
157                 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
158             */
159             else synchronized(Outgoing.class) {
160                 spool.add(m);
161                 Outgoing.class.notify();
162             }
163         }
164
165         public static boolean attempt(Message m) throws IOException {
166             if (m.envelopeTo == null) {
167                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
168                 return false;
169             }
170             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
171             if (mx.length == 0) {
172                 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
173                 accept(m.bounce("could not resolve " + m.envelopeTo.host));
174                 return true;
175             }
176             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
177                 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
178                 accept(m.bounce("could not send for 5 days"));
179                 return true;
180             }
181             for(int i=0; i<mx.length; i++) {
182                 if (deadHosts.contains(mx[i])) continue;
183                 if (attempt(m, mx[i])) { return true; }
184             }
185             return false;
186         }
187
188         private static void check(String s, Connection conn) {
189             if (s==null) return;
190             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
191             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
192         }
193         private static boolean attempt(final Message m, final InetAddress mx) {
194             boolean accepted = false;
195             Connection conn = null;
196             try {
197                 Log.note("connecting to " + mx + "...");
198                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
199                 conn.setNewline("\r\n");
200                 conn.setTimeout(60 * 1000);
201                 Log.note("    connected");
202                 check(conn.readln(), conn);  // banner
203                 try {
204                     conn.println("EHLO " + conn.vhost);
205                     check(conn.readln(), conn);
206                 } catch (SMTPException smtpe) {
207                     conn.println("HELO " + conn.vhost);
208                     check(conn.readln(), conn);
209                 }
210                 if (m.envelopeFrom==null) {
211                     Log.warn("", "MAIL FROM:<>");
212                     conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
213                 } else {
214                     Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
215                     conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">");  check(conn.readln(), conn);
216                 }
217                 conn.println("RCPT TO:<"   + m.envelopeTo.toString()+">");      check(conn.readln(), conn);
218                 conn.println("DATA");                          check(conn.readln(), conn);
219                 Headers head = m.headers;
220                 head.remove("return-path");
221                 head.remove("bcc");
222                 Stream stream = head.getStream();
223                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
224                     if (s.startsWith(".")) conn.print(".");
225                     //Log.warn("***",s);
226                     conn.println(s);
227                 }
228                 //Log.warn("***","");
229                 conn.println("");
230                 stream = m.getBody().getStream();
231                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
232                     if (s.startsWith(".")) conn.print(".");
233                     //Log.warn("***",s);
234                     conn.println(s);
235                 }
236                 conn.println(".");
237                 String resp = conn.readln();
238                 if (resp == null)
239                     throw new SMTPException("server " + mx + " closed connection without accepting message");
240                 check(resp, conn);
241                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
242                 accepted = true;
243                 conn.close();
244             } catch (Exception e) {
245                 if (accepted) return true;
246                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
247                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
248                 Log.warn(SMTP.Outgoing.class, e);
249                 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
250                 return false;
251             } finally {
252                 if (conn != null) conn.close();
253             }
254             return accepted;
255         }
256
257         static void runq() {
258             try {
259                 Log.setThreadAnnotation("[outgoing smtp] ");
260                 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
261                 while(true) {
262                     if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
263                     for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
264                         try {
265                             if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
266                             if (attempt(it.cur())) it.delete();
267                         } catch (Exception e)   {
268                             if (e instanceof InterruptedException) throw e;
269                             Log.error(SMTP.Outgoing.class, e);
270                         }
271                     }
272                     synchronized(Outgoing.class) {
273                         if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
274                         Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
275                         Outgoing.class.wait(5 * 60 * 1000);
276                         deadHosts.clear();
277                         Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
278                     }
279                 }
280             } catch (Exception e) {
281                 Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e);
282                 Log.error(SMTP.Outgoing.class, e);
283             }
284         }
285     }
286
287     public static InetAddress[] getMailExchangerIPs(String hostName) {
288         InetAddress[] ret;
289         try {
290             Hashtable env = new Hashtable();
291             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
292             DirContext ictx = new InitialDirContext(env);
293             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
294             Attribute attr = attrs.get("MX");
295             if (attr == null) {
296                 ret = new InetAddress[1];
297                 try {
298                     ret[0] = InetAddress.getByName(hostName);
299                     return ret;
300                 } catch (UnknownHostException uhe) {
301                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
302                     return new InetAddress[0];
303                 }
304             } else {
305                 ret = new InetAddress[attr.size()];
306                 NamingEnumeration ne = attr.getAll();
307                 for(int i=0; ne.hasMore();) {
308                     String mx = (String)ne.next();
309                     // FIXME we should be sorting here
310                     mx = mx.substring(mx.indexOf(" ") + 1);
311                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
312                     InetAddress ia = InetAddress.getByName(mx);
313                     if (ia.equals(IP.getIP(127,0,0,1))) continue;
314                     ret[i++] = ia;
315                 }
316             }
317         } catch (Exception e) {
318             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
319             Log.warn(SMTP.class, e);
320             return new InetAddress[0];
321         }
322         return ret;
323     }
324 }