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