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