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