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