advertise ESMTP
[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             for(String command = conn.readln(); ; command = conn.readln()) try {
97                 if (command == null) return;
98                 //Log.warn("**"+conn.getRemoteAddress()+"**", command);
99                 String c = command.toUpperCase();
100                 if (c.startsWith("HELO"))        {
101                     remotehost = c.substring(5).trim();
102                     conn.println("250 HELO " + conn.vhost);
103                     from = null; to = new Vector();
104                 } else if (c.startsWith("EHLO")) {
105                     remotehost = c.substring(5).trim();
106                     conn.println("250 "+conn.vhost+" greets " + remotehost);
107                     ehlo = true;     
108                     from = null; to = new Vector();
109                 } else if (c.startsWith("RSET")) { conn.println("250 reset ok");           from = null; to = new Vector();
110                 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help.  see a trained professional.");
111                 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
112                 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
113                 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
114                 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
115                 } else if (c.startsWith("MAIL FROM:")) {
116                     command = command.substring(10).trim();
117                     from = command.equals("<>") ? null : new Address(command);
118                     conn.println("250 " + from + " is syntactically correct");
119                 } else if (c.startsWith("RCPT TO:")) {
120                     // some clients are broken and put RCPT first; we will tolerate this
121                     command = command.substring(8).trim();
122                     if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
123                     Address addr = new Address(command);
124                     /*
125                     Log.warn("**"+conn.getRemoteAddress()+"**",
126                              "addr.isLocal(): " + addr.isLocal() + "\n" +
127                              "conn.getRemoteAddress().isLoopbackAddress(): " + conn.getRemoteAddress().isLoopbackAddress() + "\n" +
128                              "johnw: " + (from!=null&&from.toString().indexOf("johnw")!=-1) + "\n"
129                              );
130                     */
131                     if (addr.isLocal()) {
132                         // FEATURE: should check the address further and give 550 if undeliverable
133                         conn.println("250 " + addr + " is on this machine; I will deliver it");
134                         to.addElement(addr);
135                     } else if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
136                         conn.println("250 you are connected locally, so I will let you send");
137                         to.addElement(addr);
138                     } else {
139                         conn.println("551 sorry, " + addr + " is not on this machine");
140                     }
141                     conn.flush();
142                 } else if (c.startsWith("DATA")) {
143                     //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
144                     if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
145                     if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress()) {
146                         long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
147                         if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
148                             graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"",  System.currentTimeMillis());
149                             conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
150                             Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
151                             conn.flush();
152                             continue;
153                         } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
154                             graylist.addWhitelist(conn.getRemoteAddress());
155                             conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
156                             Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
157                         } else {
158                             conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
159                             conn.flush();
160                             Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
161                             continue;
162                         }
163                     } else {
164                         conn.println("354 Enter message, ending with \".\" on a line by itself");
165                     }
166                     conn.flush();
167                     try {
168                         StringBuffer buf = new StringBuffer();
169                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
170                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
171                         buf.append("          for ");
172                         // FIXME: this is leaking BCC addrs
173                         // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
174                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
175                         while(true) {
176                             String s = conn.readln();
177                             if (s == null) throw new RuntimeException("connection closed");
178                             if (s.equals(".")) break;
179                             if (s.startsWith(".")) s = s.substring(1);
180                             buf.append(s + "\r\n");
181                             if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE) {
182                                 Log.error("**"+conn.getRemoteAddress()+"**",
183                                           "sorry, this mail server only accepts messages of less than " +
184                                           ByteSize.toString(MAX_MESSAGE_SIZE));
185                                 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
186                                                                   ByteSize.toString(MAX_MESSAGE_SIZE));
187                             }
188                         }
189                         String body = buf.toString();
190                         Message m = null;
191                         for(int i=0; i<to.size(); i++) {
192                             m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
193                             accept(m);
194                         }
195                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
196                         conn.println("250 message accepted");
197                         conn.flush();
198                         from = null; to = new Vector();
199                     } catch (MailException.Malformed mfe) {    conn.println("501 " + mfe.toString());
200                     } catch (MailException.MailboxFull mbf) {  conn.println("452 " + mbf);
201                     } catch (Script.Later.LaterException le) { conn.println("453 try again later");
202                     } catch (Script.Reject.RejectException re) {
203                         Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n   " + re.m.summary());
204                         conn.println("501 " + re.reason);
205                     }
206                 } else                    { conn.println("500 unrecognized command"); }                    
207             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
208         }
209     }
210
211
212     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
213
214     public static class Outgoing extends Thread {
215
216         private static final HashMap deadHosts = new HashMap();
217         public static void accept(Message m) throws IOException {
218             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
219             String traces = m.headers.get("Received");
220             if (traces!=null) {
221                 int lines = 0;
222                 for(int i=0; i<traces.length(); i++)
223                     if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
224                         lines++;
225                 if (lines > 100) { // required by rfc
226                     Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
227                     return;
228                 }
229             }
230             synchronized(Outgoing.class) {
231                 spool.insert(m, Mailbox.Flag.defaultFlags);
232                 Outgoing.class.notifyAll();
233             }
234         }
235
236         public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
237         public static boolean attempt(Message m, boolean noBounces) throws IOException {
238             if (m.envelopeTo == null) {
239                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
240                 return false;
241             }
242             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
243             if (mx.length == 0) {
244                 if (!noBounces) {
245                     accept(m.bounce("could not resolve " + m.envelopeTo.host));
246                     return true;
247                 } else {
248                     Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
249                     return false;
250                 }
251             }
252             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
253                 if (!noBounces) {
254                     accept(m.bounce("could not send for 5 days"));
255                     return true;
256                 } else {
257                     Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
258                     return false;
259                 }
260             }
261             for(int i=0; i<mx.length; i++) {
262                 //if (deadHosts.contains(mx[i])) continue;
263                 if (attempt(m, mx[i])) { return true; }
264             }
265             return false;
266         }
267
268         private static void check(String s, Connection conn) {
269             if (s==null) return;
270             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
271             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
272         }
273         private static boolean attempt(final Message m, final InetAddress mx) {
274             boolean accepted = false;
275             Connection conn = null;
276             try {
277                 Log.note("connecting to " + mx + "...");
278                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
279                 conn.setNewline("\r\n");
280                 conn.setTimeout(60 * 1000);
281                 Log.note("    connected");
282                 check(conn.readln(), conn);  // banner
283                 try {
284                     conn.println("EHLO " + conn.vhost);
285                     check(conn.readln(), conn);
286                 } catch (SMTPException smtpe) {
287                     conn.println("HELO " + conn.vhost);
288                     check(conn.readln(), conn);
289                 }
290                 if (m.envelopeFrom==null) {
291                     Log.warn("", "MAIL FROM:<>");
292                     conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
293                 } else {
294                     Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
295                     conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">");  check(conn.readln(), conn);
296                 }
297                 conn.println("RCPT TO:<"   + m.envelopeTo.toString()+">");      check(conn.readln(), conn);
298                 conn.println("DATA");                          check(conn.readln(), conn);
299                 Headers head = m.headers;
300                 head = head.remove("return-path");
301                 head = head.remove("bcc");
302                 Stream stream = head.getStream();
303                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
304                     if (s.startsWith(".")) conn.print(".");
305                     conn.println(s);
306                 }
307                 conn.println("");
308                 stream = m.getBody().getStream();
309                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
310                     if (s.startsWith(".")) conn.print(".");
311                     conn.println(s);
312                 }
313                 conn.println(".");
314                 String resp = conn.readln();
315                 if (resp == null)
316                     throw new SMTPException("server " + mx + " closed connection without accepting message");
317                 check(resp, conn);
318                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
319                 accepted = true;
320                 conn.close();
321             } catch (SMTPException e) {
322                 if (accepted) return true;
323                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
324                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
325                 Log.warn(SMTP.Outgoing.class, e);
326                 if (e.code >= 500 && e.code <= 599) {
327                     try {
328                         attempt(m.bounce("unable to deliver: " + e), true);
329                     } catch (Exception ex) {
330                         Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
331                         Log.error(SMTP.Outgoing.class, ex);
332                     }
333                     return true;
334                 }
335                 return false;
336             } catch (Exception e) {
337                 if (accepted) return true;
338                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
339                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
340                 Log.warn(SMTP.Outgoing.class, e);
341                 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
342                 return false;
343             } finally {
344                 if (conn != null) conn.close();
345             }
346             return accepted;
347         }
348
349         private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
350         private static int serials = 1;
351         private int serial = serials++;
352         private Mailbox.Iterator it;
353
354         public Outgoing() {
355             synchronized(Outgoing.class) {
356                 threads.add(this);
357             }
358         }
359
360         public void wake() {
361             int count = spool.count(Query.all());
362             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
363             try {
364                 while(true) {
365                     boolean good = false;
366                     synchronized(Outgoing.class) {
367                         it = spool.iterator();
368                         OUTER: for(; it.next(); ) {
369                             for(Outgoing o : threads)
370                                 if (o!=this && o.it != null && o.it.uid()==it.uid())
371                                     continue OUTER;
372                             good = true;
373                             break;
374                         }
375                     }
376                     if (!good) break;
377                     try {
378                         if (attempt(it.cur())) it.delete();
379                     } catch (Exception e) {
380                         Log.error(SMTP.Outgoing.class, e);
381                     }
382                     Log.info(this, "sleeping for 3s...");
383                     Thread.sleep(3000);
384                 }
385             } catch (Exception e) {
386                 //if (e instanceof InterruptedException) throw e;
387                 Log.error(SMTP.Outgoing.class, e);
388             }
389             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
390             it = null;
391         }
392
393         public void run() {
394             try {
395                 while(true) {
396                     Log.setThreadAnnotation("[outgoing #"+serial+"] ");
397                     wake();
398                     Thread.sleep(1000);
399                     synchronized(Outgoing.class) {
400                         Outgoing.class.wait(5 * 60 * 1000);
401                     }
402                 }
403             } catch (InterruptedException e) { Log.warn(this, e); }
404         }
405     }
406
407     public static InetAddress[] getMailExchangerIPs(String hostName) {
408         InetAddress[] ret;
409         try {
410             Hashtable env = new Hashtable();
411             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
412             DirContext ictx = new InitialDirContext(env);
413             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
414             Attribute attr = attrs.get("MX");
415             if (attr == null) {
416                 ret = new InetAddress[1];
417                 try {
418                     ret[0] = InetAddress.getByName(hostName);
419                     if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
420                     return ret;
421                 } catch (UnknownHostException uhe) {
422                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
423                     return new InetAddress[0];
424                 }
425             } else {
426                 ret = new InetAddress[attr.size()];
427                 NamingEnumeration ne = attr.getAll();
428                 for(int i=0; ne.hasMore();) {
429                     String mx = (String)ne.next();
430                     // FIXME we should be sorting here
431                     mx = mx.substring(mx.indexOf(" ") + 1);
432                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
433                     InetAddress ia = InetAddress.getByName(mx);
434                     if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
435                     ret[i++] = ia;
436                 }
437             }
438         } catch (Exception e) {
439             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
440             Log.warn(SMTP.class, e);
441             return new InetAddress[0];
442         }
443         return ret;
444     }
445 }