add an extra flush in SMTP
[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: logging: current logging sucks
19 // FIXME: loop prevention
20 // FIXME: probably need some throttling on outbound mail
21
22 // graylisting?
23
24 // FEATURE: infer messageid, date, if not present (?)
25 // FEATURE: exponential backoff on retry time?
26 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
27 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
28 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
29 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
30 public class SMTP {
31
32     public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
33     public static final int numOutgoingThreads = 5;
34
35     public static final int GRAYLIST_MINWAIT =  1000 * 60 * 60;           // one hour
36     public static final int GRAYLIST_MAXWAIT =  1000 * 60 * 60 * 24 * 5;  // five days
37
38     public static final Graylist graylist =
39         new Graylist(Mailbox.STORAGE_ROOT+"/graylist.sqlite");
40
41     public static final int MAX_MESSAGE_SIZE =
42         Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
43
44     private static final Mailbox spool =
45         FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
46
47     static {
48         for(int i=0; i<numOutgoingThreads; i++)
49             new Outgoing().start();
50     }
51
52     public static void accept(Message m) throws IOException {
53         if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
54         else                         Target.root.accept(m);
55     }
56
57     public static class SMTPException extends MailException {
58         int code;
59         String message;
60         public SMTPException(String s) {
61             try {
62                 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
63                 message = s.substring(s.indexOf(' ')+1);
64             } catch (NumberFormatException nfe) {
65                 code = -1;
66                 message = s;
67             }
68         }
69         public String toString() { return "SMTP " + code + ": " + message; }
70         public String getMessage() { return toString(); }
71     }
72
73     // Server //////////////////////////////////////////////////////////////////////////////
74
75     public static class Server {
76         public void handleRequest(Connection conn) {
77             conn.setTimeout(5 * 60 * 1000);
78             conn.setNewline("\r\n");
79             conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
80             Address from = null;
81             Vector to = new Vector();
82             boolean ehlo = false;
83             String remotehost = null;
84             for(String command = conn.readln(); ; command = conn.readln()) try {
85                 if (command == null) return;
86                 Log.warn("**"+conn.getRemoteAddress()+"**", command);
87                 String c = command.toUpperCase();
88                 if (c.startsWith("HELO"))        {
89                     remotehost = c.substring(5).trim();
90                     conn.println("250 HELO " + conn.vhost);
91                     from = null; to = new Vector();
92                 } else if (c.startsWith("EHLO")) {
93                     remotehost = c.substring(5).trim();
94                     conn.println("250 "+conn.vhost+" greets " + remotehost);
95                     ehlo = true;     
96                     from = null; to = new Vector();
97                 } else if (c.startsWith("RSET")) { conn.println("250 reset ok");           from = null; to = new Vector();
98                 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help.  see a trained professional.");
99                 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
100                 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
101                 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
102                 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
103                 } else if (c.startsWith("MAIL FROM:")) {
104                     command = command.substring(10).trim();
105                     from = command.equals("<>") ? null : new Address(command);
106                     conn.println("250 " + from + " is syntactically correct");
107                 } else if (c.startsWith("RCPT TO:")) {
108                     // some clients are broken and put RCPT first; we will tolerate this
109                     command = command.substring(8).trim();
110                     if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
111                     Address addr = new Address(command);
112                     /*
113                     Log.warn("**"+conn.getRemoteAddress()+"**",
114                              "addr.isLocal(): " + addr.isLocal() + "\n" +
115                              "conn.getRemoteAddress().isLoopbackAddress(): " + conn.getRemoteAddress().isLoopbackAddress() + "\n" +
116                              "johnw: " + (from!=null&&from.toString().indexOf("johnw")!=-1) + "\n"
117                              );
118                     */
119                     if (addr.isLocal()) {
120                         // FEATURE: should check the address further and give 550 if undeliverable
121                         conn.println("250 " + addr + " is on this machine; I will deliver it");
122                         to.addElement(addr);
123                     } else if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
124                         conn.println("250 you are connected locally, so I will let you send");
125                         to.addElement(addr);
126                     } else {
127                         conn.println("551 sorry, " + addr + " is not on this machine");
128                     }
129                     conn.flush();
130                 } else if (c.startsWith("DATA")) {
131                     //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
132                     if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
133                     if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress()) {
134                         long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
135                         if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
136                             graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"",  System.currentTimeMillis());
137                             conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
138                             Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
139                             conn.flush();
140                             continue;
141                         } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
142                             graylist.addWhitelist(conn.getRemoteAddress());
143                             conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
144                             Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
145                         } else {
146                             conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
147                             conn.flush();
148                             Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
149                             continue;
150                         }
151                     } else {
152                         conn.println("354 Enter message, ending with \".\" on a line by itself");
153                     }
154                     conn.flush();
155                     try {
156                         StringBuffer buf = new StringBuffer();
157                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
158                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
159                         buf.append("          for ");
160                         // FIXME: this is leaking BCC addrs
161                         // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
162                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
163                         while(true) {
164                             String s = conn.readln();
165                             if (s == null) throw new RuntimeException("connection closed");
166                             if (s.equals(".")) break;
167                             if (s.startsWith(".")) s = s.substring(1);
168                             buf.append(s + "\r\n");
169                             if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE) {
170                                 Log.error("**"+conn.getRemoteAddress()+"**",
171                                           "sorry, this mail server only accepts messages of less than " +
172                                           ByteSize.toString(MAX_MESSAGE_SIZE));
173                                 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
174                                                                   ByteSize.toString(MAX_MESSAGE_SIZE));
175                             }
176                         }
177                         String body = buf.toString();
178                         Message m = null;
179                         for(int i=0; i<to.size(); i++) {
180                             m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
181                             accept(m);
182                         }
183                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
184                         conn.println("250 message accepted");
185                         conn.flush();
186                         from = null; to = new Vector();
187                     } catch (Reject.RejectException re) {
188                         Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n   " + re.m.summary());
189                         conn.println("501 " + re.reason);
190                     } catch (MailException.Malformed mfe) {   conn.println("501 " + mfe.toString());
191                     } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
192                     } catch (Later.LaterException le) {       conn.println("453 try again later");
193                     } catch (IOException ioe) {               
194                         //conn.println("554 " + ioe.toString());
195                         Log.error(this, ioe);
196                         conn.close();
197                         return;
198                     }
199                 } else                    { conn.println("500 unrecognized command"); }                    
200             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
201         }
202     }
203
204
205     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
206
207     public static class Outgoing extends Thread {
208
209         private static final HashMap deadHosts = new HashMap();
210         public static void accept(Message m) throws IOException {
211             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
212             String traces = m.headers.get("Received");
213             if (traces!=null) {
214                 int lines = 0;
215                 for(int i=0; i<traces.length(); i++)
216                     if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
217                         lines++;
218                 if (lines > 100) { // required by rfc
219                     Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
220                     return;
221                 }
222             }
223             synchronized(Outgoing.class) {
224                 spool.add(m);
225                 Outgoing.class.notifyAll();
226             }
227         }
228
229         public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
230         public static boolean attempt(Message m, boolean noBounces) throws IOException {
231             if (m.envelopeTo == null) {
232                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
233                 return false;
234             }
235             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
236             if (mx.length == 0) {
237                 if (!noBounces) {
238                     accept(m.bounce("could not resolve " + m.envelopeTo.host));
239                     return true;
240                 } else {
241                     Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
242                     return false;
243                 }
244             }
245             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
246                 if (!noBounces) {
247                     accept(m.bounce("could not send for 5 days"));
248                     return true;
249                 } else {
250                     Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
251                     return false;
252                 }
253             }
254             for(int i=0; i<mx.length; i++) {
255                 //if (deadHosts.contains(mx[i])) continue;
256                 if (attempt(m, mx[i])) { return true; }
257             }
258             return false;
259         }
260
261         private static void check(String s, Connection conn) {
262             if (s==null) return;
263             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
264             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
265         }
266         private static boolean attempt(final Message m, final InetAddress mx) {
267             boolean accepted = false;
268             Connection conn = null;
269             try {
270                 Log.note("connecting to " + mx + "...");
271                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
272                 conn.setNewline("\r\n");
273                 conn.setTimeout(60 * 1000);
274                 Log.note("    connected");
275                 check(conn.readln(), conn);  // banner
276                 try {
277                     conn.println("EHLO " + conn.vhost);
278                     check(conn.readln(), conn);
279                 } catch (SMTPException smtpe) {
280                     conn.println("HELO " + conn.vhost);
281                     check(conn.readln(), conn);
282                 }
283                 if (m.envelopeFrom==null) {
284                     Log.warn("", "MAIL FROM:<>");
285                     conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
286                 } else {
287                     Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
288                     conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">");  check(conn.readln(), conn);
289                 }
290                 conn.println("RCPT TO:<"   + m.envelopeTo.toString()+">");      check(conn.readln(), conn);
291                 conn.println("DATA");                          check(conn.readln(), conn);
292                 Headers head = m.headers;
293                 head = head.remove("return-path");
294                 head = head.remove("bcc");
295                 Stream stream = head.getStream();
296                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
297                     if (s.startsWith(".")) conn.print(".");
298                     conn.println(s);
299                 }
300                 conn.println("");
301                 stream = m.getBody().getStream();
302                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
303                     if (s.startsWith(".")) conn.print(".");
304                     conn.println(s);
305                 }
306                 conn.println(".");
307                 String resp = conn.readln();
308                 if (resp == null)
309                     throw new SMTPException("server " + mx + " closed connection without accepting message");
310                 check(resp, conn);
311                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
312                 accepted = true;
313                 conn.close();
314             } catch (SMTPException e) {
315                 if (accepted) return true;
316                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
317                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
318                 Log.warn(SMTP.Outgoing.class, e);
319                 if (e.code >= 500 && e.code <= 599) {
320                     try {
321                         attempt(m.bounce("unable to deliver: " + e), true);
322                     } catch (Exception ex) {
323                         Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
324                         Log.error(SMTP.Outgoing.class, ex);
325                     }
326                     return true;
327                 }
328                 return false;
329             } catch (Exception e) {
330                 if (accepted) return true;
331                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
332                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
333                 Log.warn(SMTP.Outgoing.class, e);
334                 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
335                 return false;
336             } finally {
337                 if (conn != null) conn.close();
338             }
339             return accepted;
340         }
341
342         private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
343         private static int serials = 1;
344         private int serial = serials++;
345         private Mailbox.Iterator it;
346
347         public Outgoing() {
348             synchronized(Outgoing.class) {
349                 threads.add(this);
350             }
351         }
352
353         public void wake() {
354             int count = spool.count(Query.all());
355             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
356             try {
357                 while(true) {
358                     boolean good = false;
359                     synchronized(Outgoing.class) {
360                         it = spool.iterator();
361                         OUTER: for(; it.next(); ) {
362                             for(Outgoing o : threads)
363                                 if (o!=this && o.it != null && o.it.uid()==it.uid())
364                                     continue OUTER;
365                             good = true;
366                             break;
367                         }
368                     }
369                     if (!good) break;
370                     try {
371                         if (attempt(it.cur())) it.delete();
372                     } catch (Exception e) {
373                         Log.error(SMTP.Outgoing.class, e);
374                     }
375                     Log.info(this, "sleeping for 3s...");
376                     Thread.sleep(3000);
377                 }
378             } catch (Exception e) {
379                 //if (e instanceof InterruptedException) throw e;
380                 Log.error(SMTP.Outgoing.class, e);
381             }
382             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
383             it = null;
384         }
385
386         public void run() {
387             try {
388                 while(true) {
389                     Log.setThreadAnnotation("[outgoing #"+serial+"] ");
390                     wake();
391                     Thread.sleep(1000);
392                     synchronized(Outgoing.class) {
393                         Outgoing.class.wait(5 * 60 * 1000);
394                     }
395                 }
396             } catch (InterruptedException e) { Log.warn(this, e); }
397         }
398     }
399
400     public static InetAddress[] getMailExchangerIPs(String hostName) {
401         InetAddress[] ret;
402         try {
403             Hashtable env = new Hashtable();
404             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
405             DirContext ictx = new InitialDirContext(env);
406             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
407             Attribute attr = attrs.get("MX");
408             if (attr == null) {
409                 ret = new InetAddress[1];
410                 try {
411                     ret[0] = InetAddress.getByName(hostName);
412                     if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
413                     return ret;
414                 } catch (UnknownHostException uhe) {
415                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
416                     return new InetAddress[0];
417                 }
418             } else {
419                 ret = new InetAddress[attr.size()];
420                 NamingEnumeration ne = attr.getAll();
421                 for(int i=0; ne.hasMore();) {
422                     String mx = (String)ne.next();
423                     // FIXME we should be sorting here
424                     mx = mx.substring(mx.indexOf(" ") + 1);
425                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
426                     InetAddress ia = InetAddress.getByName(mx);
427                     if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
428                     ret[i++] = ia;
429                 }
430             }
431         } catch (Exception e) {
432             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
433             Log.warn(SMTP.class, e);
434             return new InetAddress[0];
435         }
436         return ret;
437     }
438 }