35855f152cd6fd2f8f006edde0ef5a4d2a9542bc
[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) throws IOException {
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                     }
195                 } else                    { conn.println("500 unrecognized command"); }                    
196             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
197         }
198     }
199
200
201     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
202
203     public static class Outgoing extends Thread {
204
205         private static final HashMap deadHosts = new HashMap();
206         public static void accept(Message m) throws IOException {
207             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
208             String traces = m.headers.get("Received");
209             if (traces!=null) {
210                 int lines = 0;
211                 for(int i=0; i<traces.length(); i++)
212                     if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
213                         lines++;
214                 if (lines > 100) { // required by rfc
215                     Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
216                     return;
217                 }
218             }
219             synchronized(Outgoing.class) {
220                 spool.insert(m, Mailbox.Flag.defaultFlags);
221                 Outgoing.class.notifyAll();
222             }
223         }
224
225         public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
226         public static boolean attempt(Message m, boolean noBounces) throws IOException {
227             if (m.envelopeTo == null) {
228                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
229                 return false;
230             }
231             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
232             if (mx.length == 0) {
233                 if (!noBounces) {
234                     accept(m.bounce("could not resolve " + m.envelopeTo.host));
235                     return true;
236                 } else {
237                     Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
238                     return false;
239                 }
240             }
241             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
242                 if (!noBounces) {
243                     accept(m.bounce("could not send for 5 days"));
244                     return true;
245                 } else {
246                     Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
247                     return false;
248                 }
249             }
250             for(int i=0; i<mx.length; i++) {
251                 //if (deadHosts.contains(mx[i])) continue;
252                 if (attempt(m, mx[i])) { return true; }
253             }
254             return false;
255         }
256
257         private static void check(String s, Connection conn) {
258             if (s==null) return;
259             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
260             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
261         }
262         private static boolean attempt(final Message m, final InetAddress mx) {
263             boolean accepted = false;
264             Connection conn = null;
265             try {
266                 Log.note("connecting to " + mx + "...");
267                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
268                 conn.setNewline("\r\n");
269                 conn.setTimeout(60 * 1000);
270                 Log.note("    connected");
271                 check(conn.readln(), conn);  // banner
272                 try {
273                     conn.println("EHLO " + conn.vhost);
274                     check(conn.readln(), conn);
275                 } catch (SMTPException smtpe) {
276                     conn.println("HELO " + conn.vhost);
277                     check(conn.readln(), conn);
278                 }
279                 if (m.envelopeFrom==null) {
280                     Log.warn("", "MAIL FROM:<>");
281                     conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
282                 } else {
283                     Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
284                     conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">");  check(conn.readln(), conn);
285                 }
286                 conn.println("RCPT TO:<"   + m.envelopeTo.toString()+">");      check(conn.readln(), conn);
287                 conn.println("DATA");                          check(conn.readln(), conn);
288                 Headers head = m.headers;
289                 head = head.remove("return-path");
290                 head = head.remove("bcc");
291                 Stream stream = head.getStream();
292                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
293                     if (s.startsWith(".")) conn.print(".");
294                     conn.println(s);
295                 }
296                 conn.println("");
297                 stream = m.getBody().getStream();
298                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
299                     if (s.startsWith(".")) conn.print(".");
300                     conn.println(s);
301                 }
302                 conn.println(".");
303                 String resp = conn.readln();
304                 if (resp == null)
305                     throw new SMTPException("server " + mx + " closed connection without accepting message");
306                 check(resp, conn);
307                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
308                 accepted = true;
309                 conn.close();
310             } catch (SMTPException e) {
311                 if (accepted) return true;
312                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
313                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
314                 Log.warn(SMTP.Outgoing.class, e);
315                 if (e.code >= 500 && e.code <= 599) {
316                     try {
317                         attempt(m.bounce("unable to deliver: " + e), true);
318                     } catch (Exception ex) {
319                         Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
320                         Log.error(SMTP.Outgoing.class, ex);
321                     }
322                     return true;
323                 }
324                 return false;
325             } catch (Exception e) {
326                 if (accepted) return true;
327                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
328                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
329                 Log.warn(SMTP.Outgoing.class, e);
330                 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
331                 return false;
332             } finally {
333                 if (conn != null) conn.close();
334             }
335             return accepted;
336         }
337
338         private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
339         private static int serials = 1;
340         private int serial = serials++;
341         private Mailbox.Iterator it;
342
343         public Outgoing() {
344             synchronized(Outgoing.class) {
345                 threads.add(this);
346             }
347         }
348
349         public void wake() {
350             int count = spool.count(Query.all());
351             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
352             try {
353                 while(true) {
354                     boolean good = false;
355                     synchronized(Outgoing.class) {
356                         it = spool.iterator();
357                         OUTER: for(; it.next(); ) {
358                             for(Outgoing o : threads)
359                                 if (o!=this && o.it != null && o.it.uid()==it.uid())
360                                     continue OUTER;
361                             good = true;
362                             break;
363                         }
364                     }
365                     if (!good) break;
366                     try {
367                         if (attempt(it.cur())) it.delete();
368                     } catch (Exception e) {
369                         Log.error(SMTP.Outgoing.class, e);
370                     }
371                     Log.info(this, "sleeping for 3s...");
372                     Thread.sleep(3000);
373                 }
374             } catch (Exception e) {
375                 //if (e instanceof InterruptedException) throw e;
376                 Log.error(SMTP.Outgoing.class, e);
377             }
378             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
379             it = null;
380         }
381
382         public void run() {
383             try {
384                 while(true) {
385                     Log.setThreadAnnotation("[outgoing #"+serial+"] ");
386                     wake();
387                     Thread.sleep(1000);
388                     synchronized(Outgoing.class) {
389                         Outgoing.class.wait(5 * 60 * 1000);
390                     }
391                 }
392             } catch (InterruptedException e) { Log.warn(this, e); }
393         }
394     }
395
396     public static InetAddress[] getMailExchangerIPs(String hostName) {
397         InetAddress[] ret;
398         try {
399             Hashtable env = new Hashtable();
400             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
401             DirContext ictx = new InitialDirContext(env);
402             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
403             Attribute attr = attrs.get("MX");
404             if (attr == null) {
405                 ret = new InetAddress[1];
406                 try {
407                     ret[0] = InetAddress.getByName(hostName);
408                     if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
409                     return ret;
410                 } catch (UnknownHostException uhe) {
411                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
412                     return new InetAddress[0];
413                 }
414             } else {
415                 ret = new InetAddress[attr.size()];
416                 NamingEnumeration ne = attr.getAll();
417                 for(int i=0; ne.hasMore();) {
418                     String mx = (String)ne.next();
419                     // FIXME we should be sorting here
420                     mx = mx.substring(mx.indexOf(" ") + 1);
421                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
422                     InetAddress ia = InetAddress.getByName(mx);
423                     if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
424                     ret[i++] = ia;
425                 }
426             }
427         } catch (Exception e) {
428             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
429             Log.warn(SMTP.class, e);
430             return new InetAddress[0];
431         }
432         return ret;
433     }
434 }