db5da88316c902bfdb151e79b9160d29408b05e6
[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
15 // FIXME: inbound throttling/ratelimiting
16
17 // "Address enumeration detection" -- notice when it looks like somebody
18 // is trying a raft of addresses.
19
20 // RFC's implemented
21 // RFC2554: SMTP Service Extension for Authentication
22 //     - did not implement section 5, though
23 // RFC4616: SASL PLAIN
24
25 // Note: we can't actually use status codes for feedback if we accept
26 // multiple destination addresses...  a failure on one and success on
27 // the other...
28
29 // FIXME: logging: current logging sucks
30 // FIXME: loop prevention
31 // FIXME: probably need some throttling on outbound mail
32
33 // FEATURE: public static boolean validate(Address a)
34 // FEATURE: rate-limiting
35
36 // FEATURE: infer messageid, date, if not present (?)
37 // FEATURE: exponential backoff on retry time?
38 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
39 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
40 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
41 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
42 public class SMTP {
43
44     public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
45     public static final int numOutgoingThreads = 5;
46
47     private static final SqliteMailbox allmail =
48         (SqliteMailbox)FileBasedMailbox
49         .getFileBasedMailbox("/afs/megacz.com/mail/user/megacz/allmail", false);
50
51     public static final int GRAYLIST_MINWAIT =  1000 * 60 * 60;           // one hour
52     public static final int GRAYLIST_MAXWAIT =  1000 * 60 * 60 * 24 * 5;  // five days
53
54     public static final int RETRY_TIME = 1000 * 60 * 30;
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                     // Don't perform SAV; discouraged here
201                     //   http://blog.fastmail.fm/2007/12/05/sending-email-servers-best-practice/
202                 } else if (c.startsWith("RCPT TO:")) {
203                     // some clients are broken and put RCPT first; we will tolerate this
204                     command = command.substring(8).trim();
205                     if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
206                     Address addr = new Address(command);
207                     if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
208                         conn.println("250 you are connected locally, so I will let you send");
209                         to.addElement(addr);
210                         if (!whitelist.isWhitelisted(addr))
211                             whitelist.addWhitelist(addr);
212                     } else if (authenticatedAs!=null) {
213                         conn.println("250 you are authenticated as "+authenticatedAs+", so I will let you send");
214                         to.addElement(addr);
215                         if (!whitelist.isWhitelisted(addr))
216                             whitelist.addWhitelist(addr);
217                     } else if (addr.isLocal()) {
218                         if (to.size() > 3) {
219                             conn.println("536 sorry, limit on 3 RCPT TO's per DATA");
220                         } else {
221                             // FEATURE: should check the address further and give 550 if undeliverable
222                             conn.println("250 " + addr + " is on this machine; I will deliver it");
223                             to.addElement(addr);
224                         }
225                     } else {
226                         conn.println("535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
227                         Log.warn("","535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
228                         failedRcptCount++;
229                         if (failedRcptCount > 3) {
230                             conn.close();
231                             return;
232                         }
233                     }
234                     conn.flush();
235                 } else if (c.startsWith("DATA")) {
236                     //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
237                     if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
238                     if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress() && authenticatedAs==null) {
239                         long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
240                         if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
241                             graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"",  System.currentTimeMillis());
242                             conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
243                             Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
244                             conn.flush();
245                             continue;
246                         } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
247                             graylist.addWhitelist(conn.getRemoteAddress());
248                             conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
249                             Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
250                         } else {
251                             conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
252                             conn.flush();
253                             Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
254                             continue;
255                         }
256                     } else {
257                         conn.println("354 Enter message, ending with \".\" on a line by itself");
258                     }
259                     conn.flush();
260                     try {
261                         // FIXME: deal with messages larger than memory here?
262                         StringBuffer buf = new StringBuffer();
263                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
264                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
265                         buf.append("          for ");
266                         // FIXME: this is leaking BCC addrs
267                         // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
268                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
269
270                         // FIXME: some sort of stream transformer here?
271                         while(true) {
272                             String s = conn.readln();
273                             if (s == null) throw new RuntimeException("connection closed");
274                             if (s.equals(".")) break;
275                             if (s.startsWith(".")) s = s.substring(1);
276                             buf.append(s + "\r\n");
277                             if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE && (from+"").indexOf("paperless")==-1) {
278                                 Log.error("**"+conn.getRemoteAddress()+"**",
279                                           "sorry, this mail server only accepts messages of less than " +
280                                           ByteSize.toString(MAX_MESSAGE_SIZE));
281                                 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
282                                                                   ByteSize.toString(MAX_MESSAGE_SIZE));
283                             }
284                         }
285                         String message = buf.toString();
286                         Message m = null;
287                         for(int i=0; i<to.size(); i++)
288                             enqueue(m = Message.newMessage(Fountain.Util.create(message)).withEnvelope(from, (Address)to.elementAt(i)));
289                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
290                         conn.println("250 message accepted");
291                         conn.flush();
292                         from = null; to = new Vector();
293                     } catch (MailException.Malformed mfe) {    conn.println("501 " + mfe.toString());
294                     } catch (MailException.MailboxFull mbf) {  conn.println("452 " + mbf);
295                     } catch (Script.Later.LaterException le) { conn.println("453 try again later");
296                     } catch (Script.Reject.RejectException re) {
297                         Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n   " + re.m.summary());
298                         conn.println("501 " + re.reason);
299                     }
300                 } else                    { conn.println("500 unrecognized command"); }                    
301             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
302         }
303     }
304
305
306     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
307
308     public static class Outgoing extends Thread {
309
310         private static final HashMap deadHosts = new HashMap();
311         public static void enqueue(Message m) throws IOException {
312             if (m == null) { Log.warn(Outgoing.class, "attempted to enqueue(null)"); return; }
313             String traces = m.headers.get("Received");
314             if (traces!=null) {
315                 int lines = 0;
316                 for(int i=0; i<traces.length(); i++)
317                     if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
318                         lines++;
319                 if (lines > 100) { // required by rfc
320                     Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
321                     return;
322                 }
323             }
324             synchronized(Outgoing.class) {
325                 spool.insert(m, Mailbox.Flag.defaultFlags);
326                 Outgoing.class.notifyAll();
327             }
328         }
329
330         public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
331         public static boolean attempt(Message m, boolean noBounces) throws IOException {
332             if (m.envelopeTo == null) {
333                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
334                 return false;
335             }
336             InetAddress[] mx = DNSUtil.getMailExchangerIPs(m.envelopeTo.host);
337             if (mx.length == 0) {
338                 if (!noBounces) {
339                     enqueue(m.bounce("could not resolve " + m.envelopeTo.host));
340                     return true;
341                 } else {
342                     Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
343                     return false;
344                 }
345             }
346             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
347                 if (!noBounces) {
348                     enqueue(m.bounce("could not send for 5 days"));
349                     return true;
350                 } else {
351                     Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
352                     return false;
353                 }
354             }
355             for(int i=0; i<mx.length; i++) {
356                 //if (deadHosts.contains(mx[i])) continue;
357                 if (attempt(m, mx[i])) return true;
358             }
359             return false;
360         }
361
362         private static void check(String s, Connection conn) {
363             if (s==null) return;
364             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
365             //if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
366             if (!s.startsWith("2")&&!s.startsWith("3")) throw new SMTPException(s);
367         }
368         private static boolean attempt(final Message m, final InetAddress mx) {
369             boolean accepted = false;
370             Connection conn = null;
371             try {
372                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
373                 InetAddress localAddress = conn.getSocket().getLocalAddress();
374                 String reverse = DNSUtil.reverseLookup(localAddress);
375                 Log.info(SMTP.Outgoing.class,
376                          "outbound connection to " + mx + " uses " + localAddress + " [reverse: " + reverse + "]");
377                 InetAddress relookup = InetAddress.getByName(reverse);
378                 if (!relookup.equals(localAddress))
379                     Log.error(SMTP.Outgoing.class,
380                               "Warning: local machine fails forward-confirmed-reverse; " +
381                               reverse + " resolves to " + localAddress);
382                 conn.setNewline("\r\n");
383                 conn.setTimeout(60 * 1000);
384                 check(conn.readln(), conn);  // banner
385                 try {
386                     conn.println("EHLO " + reverse);
387                     check(conn.readln(), conn);
388                 } catch (SMTPException smtpe) {
389                     conn.println("HELO " + reverse);
390                     check(conn.readln(), conn);
391                 }
392                 String envelopeFrom = m.envelopeFrom==null ? "" : m.envelopeFrom.toString();
393                 conn.println("MAIL FROM:<" + envelopeFrom +">");            check(conn.readln(), conn);
394                 conn.println("RCPT TO:<"   + m.envelopeTo.toString()+">");  check(conn.readln(), conn);
395                 conn.println("DATA");                                       check(conn.readln(), conn);
396
397                 Headers head = new Headers(m.headers,
398                                            new String[] {
399                                                "return-path", null,
400                                                "bcc", null
401                                            });
402                 Stream stream = head.getStream();
403                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
404                     if (s.startsWith(".")) conn.print(".");
405                     conn.println(s);
406                 }
407                 conn.println("");
408                 stream = m.getBody().getStream();
409                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
410                     if (s.startsWith(".")) conn.print(".");
411                     conn.println(s);
412                 }
413                 conn.println(".");
414                 String resp = conn.readln();
415                 if (resp == null)
416                     throw new SMTPException("server " + mx + " closed connection without accepting message");
417                 check(resp, conn);
418                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
419                 accepted = true;
420                 conn.close();
421             } catch (SMTPException e) {
422                 if (accepted) return true;
423                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
424                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
425                 Log.warn(SMTP.Outgoing.class, e);
426                 /*
427                   // FIXME: we should not be bouncing here!
428                 if (e.code >= 500 && e.code <= 599) {
429                     try {
430                         attempt(m.bounce("unable to deliver: " + e), true);
431                     } catch (Exception ex) {
432                         Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
433                         Log.error(SMTP.Outgoing.class, ex);
434                     }
435                     return true;
436                 }
437                 */
438                 return false;
439             } catch (Exception e) {
440                 if (accepted) return true;
441                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
442                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
443                 Log.warn(SMTP.Outgoing.class, e);
444                 //if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
445                 return false;
446             } finally {
447                 if (conn != null) conn.close();
448             }
449             return accepted;
450         }
451
452         private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
453         private static int serials = 1;
454         private int serial = serials++;
455         private Mailbox.Iterator it;
456
457         private static Map<String,Long> nextTry = Collections.synchronizedMap(new HashMap<String,Long>());
458
459         public Outgoing() {
460             synchronized(Outgoing.class) {
461                 threads.add(this);
462             }
463         }
464
465         public void wake() {
466             int count = spool.count(Query.all());
467             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
468             try {
469                 while(true) {
470                     boolean good = false;
471                     synchronized(Outgoing.class) {
472                         it = spool.iterator();
473                         OUTER: for(; it.next(); ) {
474                             for(Outgoing o : threads)
475                                 if (o!=this && o.it != null && o.it.uid()==it.uid())
476                                     continue OUTER;
477                             good = true;
478                             break;
479                         }
480                     }
481                     if (!good) break;
482                     try {
483                         String messageid = it.cur().messageid;
484                         if (nextTry.get(messageid) == null || System.currentTimeMillis() > nextTry.get(messageid)) {
485                             boolean ok = attempt(it.cur());
486                             if (ok) it.delete();
487                             else nextTry.put(messageid, System.currentTimeMillis() + RETRY_TIME);
488                         }
489                     } catch (Exception e) {
490                         Log.error(SMTP.Outgoing.class, e);
491                     }
492                     Log.info(this, "sleeping for 3s...");
493                     Thread.sleep(3000);
494                 }
495             } catch (Exception e) {
496                 //if (e instanceof InterruptedException) throw e;
497                 Log.error(SMTP.Outgoing.class, e);
498             }
499             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
500             it = null;
501         }
502
503         public void run() {
504             try {
505                 while(true) {
506                     Log.setThreadAnnotation("[outgoing #"+serial+"] ");
507                     wake();
508                     Thread.sleep(1000);
509                     synchronized(Outgoing.class) {
510                         Outgoing.class.wait(5 * 60 * 1000);
511                     }
512                 }
513             } catch (InterruptedException e) { Log.warn(this, e); }
514         }
515     }
516
517 }