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