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