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