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