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