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