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