be67a0edb91e680156a8a7590d8ef59f2bddab73
[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                 } else if (c.startsWith("DATA")) {
130                     //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
131                     if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
132                     if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress()) {
133                         long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
134                         if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
135                             graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"",  System.currentTimeMillis());
136                             conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
137                             Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
138                             conn.flush();
139                             continue;
140                         } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
141                             graylist.addWhitelist(conn.getRemoteAddress());
142                             conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
143                             Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
144                         } else {
145                             conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
146                             conn.flush();
147                             Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
148                             continue;
149                         }
150                     } else {
151                         conn.println("354 Enter message, ending with \".\" on a line by itself");
152                     }
153                     conn.flush();
154                     try {
155                         StringBuffer buf = new StringBuffer();
156                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
157                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
158                         buf.append("          for ");
159                         // FIXME: this is leaking BCC addrs
160                         // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
161                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
162                         while(true) {
163                             String s = conn.readln();
164                             if (s == null) throw new RuntimeException("connection closed");
165                             if (s.equals(".")) break;
166                             if (s.startsWith(".")) s = s.substring(1);
167                             buf.append(s + "\r\n");
168                         }
169                         String body = buf.toString();
170                         Message m = null;
171                         for(int i=0; i<to.size(); i++) {
172                             m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
173                             accept(m);
174                         }
175                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
176                         conn.println("250 message accepted");
177                         conn.flush();
178                         from = null; to = new Vector();
179                     } catch (Reject.RejectException re) {
180                         Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n   " + re.m.summary());
181                         conn.println("501 " + re.reason);
182                     } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
183                     } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
184                     } catch (Later.LaterException le) {       conn.println("453 try again later");
185                     } catch (IOException ioe) {               
186                         //conn.println("554 " + ioe.toString());
187                         Log.error(this, ioe);
188                         conn.close();
189                         return;
190                     }
191                 } else                    { conn.println("500 unrecognized command"); }                    
192             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
193         }
194     }
195
196
197     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
198
199     public static class Outgoing extends Thread {
200
201         private static final HashSet deadHosts = new HashSet();
202         public static void accept(Message m) throws IOException {
203             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
204             String traces = m.headers.get("Received");
205             if (traces!=null) {
206                 int lines = 0;
207                 for(int i=0; i<traces.length(); i++)
208                     if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
209                         lines++;
210                 if (lines > 100) { // required by rfc
211                     Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
212                     return;
213                 }
214             }
215             synchronized(Outgoing.class) {
216                 spool.add(m);
217                 Outgoing.class.notifyAll();
218             }
219         }
220
221         public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
222         public static boolean attempt(Message m, boolean noBounces) throws IOException {
223             if (m.envelopeTo == null) {
224                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
225                 return false;
226             }
227             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
228             if (mx.length == 0) {
229                 if (!noBounces) {
230                     accept(m.bounce("could not resolve " + m.envelopeTo.host));
231                     return true;
232                 } else {
233                     Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
234                     return false;
235                 }
236             }
237             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
238                 if (!noBounces) {
239                     accept(m.bounce("could not send for 5 days"));
240                     return true;
241                 } else {
242                     Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
243                     return false;
244                 }
245             }
246             for(int i=0; i<mx.length; i++) {
247                 //if (deadHosts.contains(mx[i])) continue;
248                 if (attempt(m, mx[i])) { return true; }
249             }
250             return false;
251         }
252
253         private static void check(String s, Connection conn) {
254             if (s==null) return;
255             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
256             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
257         }
258         private static boolean attempt(final Message m, final InetAddress mx) {
259             boolean accepted = false;
260             Connection conn = null;
261             try {
262                 Log.note("connecting to " + mx + "...");
263                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
264                 conn.setNewline("\r\n");
265                 conn.setTimeout(60 * 1000);
266                 Log.note("    connected");
267                 check(conn.readln(), conn);  // banner
268                 try {
269                     conn.println("EHLO " + conn.vhost);
270                     check(conn.readln(), conn);
271                 } catch (SMTPException smtpe) {
272                     conn.println("HELO " + conn.vhost);
273                     check(conn.readln(), conn);
274                 }
275                 if (m.envelopeFrom==null) {
276                     Log.warn("", "MAIL FROM:<>");
277                     conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
278                 } else {
279                     Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
280                     conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">");  check(conn.readln(), conn);
281                 }
282                 conn.println("RCPT TO:<"   + m.envelopeTo.toString()+">");      check(conn.readln(), conn);
283                 conn.println("DATA");                          check(conn.readln(), conn);
284                 Headers head = m.headers;
285                 head = head.remove("return-path");
286                 head = head.remove("bcc");
287                 Stream stream = head.getStream();
288                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
289                     if (s.startsWith(".")) conn.print(".");
290                     conn.println(s);
291                 }
292                 conn.println("");
293                 stream = m.getBody().getStream();
294                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
295                     if (s.startsWith(".")) conn.print(".");
296                     conn.println(s);
297                 }
298                 conn.println(".");
299                 String resp = conn.readln();
300                 if (resp == null)
301                     throw new SMTPException("server " + mx + " closed connection without accepting message");
302                 check(resp, conn);
303                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
304                 accepted = true;
305                 conn.close();
306             } catch (SMTPException e) {
307                 if (accepted) return true;
308                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
309                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
310                 Log.warn(SMTP.Outgoing.class, e);
311                 if (e.code >= 500 && e.code <= 599) {
312                     try {
313                         attempt(m.bounce("unable to deliver: " + e), true);
314                     } catch (Exception ex) {
315                         Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
316                         Log.error(SMTP.Outgoing.class, ex);
317                     }
318                     return true;
319                 }
320                 return false;
321             } catch (Exception e) {
322                 if (accepted) return true;
323                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
324                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
325                 Log.warn(SMTP.Outgoing.class, e);
326                 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
327                 return false;
328             } finally {
329                 if (conn != null) conn.close();
330             }
331             return accepted;
332         }
333
334         private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
335         private static int serials = 1;
336         private int serial = serials++;
337         private Mailbox.Iterator it;
338
339         public Outgoing() {
340             synchronized(Outgoing.class) {
341                 threads.add(this);
342             }
343         }
344
345         public void wake() {
346             int count = spool.count(Query.all());
347             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
348             try {
349                 while(true) {
350                     boolean good = false;
351                     synchronized(Outgoing.class) {
352                         it = spool.iterator();
353                         OUTER: for(; it.next(); ) {
354                             for(Outgoing o : threads)
355                                 if (o!=this && o.it != null && o.it.uid()==it.uid())
356                                     continue OUTER;
357                             good = true;
358                             break;
359                         }
360                     }
361                     if (!good) break;
362                     try {
363                         if (attempt(it.cur())) it.delete();
364                     } catch (Exception e) {
365                         Log.error(SMTP.Outgoing.class, e);
366                     }
367                     Log.info(this, "sleeping for 3s...");
368                     Thread.sleep(3000);
369                 }
370             } catch (Exception e) {
371                 //if (e instanceof InterruptedException) throw e;
372                 Log.error(SMTP.Outgoing.class, e);
373             }
374             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
375             it = null;
376         }
377
378         public void run() {
379             try {
380                 while(true) {
381                     Log.setThreadAnnotation("[outgoing #"+serial+"] ");
382                     wake();
383                     Thread.sleep(1000);
384                     synchronized(Outgoing.class) {
385                         Outgoing.class.wait(5 * 60 * 1000);
386                     }
387                 }
388             } catch (InterruptedException e) { Log.warn(this, e); }
389         }
390     }
391
392     public static InetAddress[] getMailExchangerIPs(String hostName) {
393         InetAddress[] ret;
394         try {
395             Hashtable env = new Hashtable();
396             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
397             DirContext ictx = new InitialDirContext(env);
398             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
399             Attribute attr = attrs.get("MX");
400             if (attr == null) {
401                 ret = new InetAddress[1];
402                 try {
403                     ret[0] = InetAddress.getByName(hostName);
404                     if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
405                     return ret;
406                 } catch (UnknownHostException uhe) {
407                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
408                     return new InetAddress[0];
409                 }
410             } else {
411                 ret = new InetAddress[attr.size()];
412                 NamingEnumeration ne = attr.getAll();
413                 for(int i=0; ne.hasMore();) {
414                     String mx = (String)ne.next();
415                     // FIXME we should be sorting here
416                     mx = mx.substring(mx.indexOf(" ") + 1);
417                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
418                     InetAddress ia = InetAddress.getByName(mx);
419                     if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
420                     ret[i++] = ia;
421                 }
422             }
423         } catch (Exception e) {
424             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
425             Log.warn(SMTP.class, e);
426             return new InetAddress[0];
427         }
428         return ret;
429     }
430 }