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.
5 package org.ibex.mail.protocol;
6 import org.ibex.mail.*;
7 import org.ibex.mail.target.*;
8 import org.ibex.util.*;
15 import javax.naming.*;
16 import javax.naming.directory.*;
18 // FIXME: logging: current logging sucks
19 // FIXME: loop prevention
20 // FIXME: probably need some throttling on outbound mail
22 // FEATURE: infer messageid, date, if not present (?)
23 // FEATURE: exponential backoff on retry time?
24 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
25 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
26 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
27 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
30 public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
31 public static final int numOutgoingThreads = 5;
33 public static final int GRAYLIST_MINWAIT = 1000 * 60 * 60; // one hour
34 public static final int GRAYLIST_MAXWAIT = 1000 * 60 * 60 * 24 * 5; // five days
36 public static final Graylist graylist =
37 new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite");
39 public static final Whitelist whitelist =
40 new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite");
42 public static final int MAX_MESSAGE_SIZE =
43 Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
45 private static final Mailbox spool =
46 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
49 for(int i=0; i<numOutgoingThreads; i++)
50 new Outgoing().start();
53 public static void accept(Message m) throws IOException {
54 if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
55 else Target.root.accept(m);
58 public static class SMTPException extends MailException {
61 public SMTPException(String s) {
63 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
64 message = s.substring(s.indexOf(' ')+1);
65 } catch (NumberFormatException nfe) {
70 public String toString() { return "SMTP " + code + ": " + message; }
71 public String getMessage() { return toString(); }
74 // Server //////////////////////////////////////////////////////////////////////////////
76 public static class Server {
77 public void handleRequest(Connection conn) {
78 conn.setTimeout(5 * 60 * 1000);
79 conn.setNewline("\r\n");
80 conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
82 Vector to = new Vector();
84 String remotehost = null;
85 for(String command = conn.readln(); ; command = conn.readln()) try {
86 if (command == null) return;
87 Log.warn("**"+conn.getRemoteAddress()+"**", command);
88 String c = command.toUpperCase();
89 if (c.startsWith("HELO")) {
90 remotehost = c.substring(5).trim();
91 conn.println("250 HELO " + conn.vhost);
92 from = null; to = new Vector();
93 } else if (c.startsWith("EHLO")) {
94 remotehost = c.substring(5).trim();
95 conn.println("250 "+conn.vhost+" greets " + remotehost);
97 from = null; to = new Vector();
98 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
99 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
100 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
101 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
102 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
103 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
104 } else if (c.startsWith("MAIL FROM:")) {
105 command = command.substring(10).trim();
106 from = command.equals("<>") ? null : new Address(command);
107 conn.println("250 " + from + " is syntactically correct");
108 } else if (c.startsWith("RCPT TO:")) {
109 // some clients are broken and put RCPT first; we will tolerate this
110 command = command.substring(8).trim();
111 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
112 Address addr = new Address(command);
114 Log.warn("**"+conn.getRemoteAddress()+"**",
115 "addr.isLocal(): " + addr.isLocal() + "\n" +
116 "conn.getRemoteAddress().isLoopbackAddress(): " + conn.getRemoteAddress().isLoopbackAddress() + "\n" +
117 "johnw: " + (from!=null&&from.toString().indexOf("johnw")!=-1) + "\n"
120 if (addr.isLocal()) {
121 // FEATURE: should check the address further and give 550 if undeliverable
122 conn.println("250 " + addr + " is on this machine; I will deliver it");
124 } else if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
125 conn.println("250 you are connected locally, so I will let you send");
128 conn.println("551 sorry, " + addr + " is not on this machine");
131 } else if (c.startsWith("DATA")) {
132 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
133 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
134 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress()) {
135 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
136 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
137 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
138 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
139 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
142 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
143 graylist.addWhitelist(conn.getRemoteAddress());
144 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
145 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
147 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
149 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
153 conn.println("354 Enter message, ending with \".\" on a line by itself");
157 StringBuffer buf = new StringBuffer();
158 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
159 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
161 // FIXME: this is leaking BCC addrs
162 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
163 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
165 String s = conn.readln();
166 if (s == null) throw new RuntimeException("connection closed");
167 if (s.equals(".")) break;
168 if (s.startsWith(".")) s = s.substring(1);
169 buf.append(s + "\r\n");
170 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE) {
171 Log.error("**"+conn.getRemoteAddress()+"**",
172 "sorry, this mail server only accepts messages of less than " +
173 ByteSize.toString(MAX_MESSAGE_SIZE));
174 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
175 ByteSize.toString(MAX_MESSAGE_SIZE));
178 String body = buf.toString();
180 for(int i=0; i<to.size(); i++) {
181 m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
184 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
185 conn.println("250 message accepted");
187 from = null; to = new Vector();
188 } catch (Reject.RejectException re) {
189 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
190 conn.println("501 " + re.reason);
191 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
192 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
193 } catch (Later.LaterException le) { conn.println("453 try again later");
194 } catch (IOException ioe) {
195 //conn.println("554 " + ioe.toString());
196 Log.error(this, ioe);
200 } else { conn.println("500 unrecognized command"); }
201 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
206 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
208 public static class Outgoing extends Thread {
210 private static final HashMap deadHosts = new HashMap();
211 public static void accept(Message m) throws IOException {
212 if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
213 String traces = m.headers.get("Received");
216 for(int i=0; i<traces.length(); i++)
217 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
219 if (lines > 100) { // required by rfc
220 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
224 synchronized(Outgoing.class) {
226 Outgoing.class.notifyAll();
230 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
231 public static boolean attempt(Message m, boolean noBounces) throws IOException {
232 if (m.envelopeTo == null) {
233 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
236 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
237 if (mx.length == 0) {
239 accept(m.bounce("could not resolve " + m.envelopeTo.host));
242 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
246 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
248 accept(m.bounce("could not send for 5 days"));
251 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
255 for(int i=0; i<mx.length; i++) {
256 //if (deadHosts.contains(mx[i])) continue;
257 if (attempt(m, mx[i])) { return true; }
262 private static void check(String s, Connection conn) {
264 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
265 if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
267 private static boolean attempt(final Message m, final InetAddress mx) {
268 boolean accepted = false;
269 Connection conn = null;
271 Log.note("connecting to " + mx + "...");
272 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
273 conn.setNewline("\r\n");
274 conn.setTimeout(60 * 1000);
275 Log.note(" connected");
276 check(conn.readln(), conn); // banner
278 conn.println("EHLO " + conn.vhost);
279 check(conn.readln(), conn);
280 } catch (SMTPException smtpe) {
281 conn.println("HELO " + conn.vhost);
282 check(conn.readln(), conn);
284 if (m.envelopeFrom==null) {
285 Log.warn("", "MAIL FROM:<>");
286 conn.println("MAIL FROM:<>"); check(conn.readln(), conn);
288 Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
289 conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">"); check(conn.readln(), conn);
291 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
292 conn.println("DATA"); check(conn.readln(), conn);
293 Headers head = m.headers;
294 head = head.remove("return-path");
295 head = head.remove("bcc");
296 Stream stream = head.getStream();
297 for(String s = stream.readln(); s!=null; s=stream.readln()) {
298 if (s.startsWith(".")) conn.print(".");
302 stream = m.getBody().getStream();
303 for(String s = stream.readln(); s!=null; s=stream.readln()) {
304 if (s.startsWith(".")) conn.print(".");
308 String resp = conn.readln();
310 throw new SMTPException("server " + mx + " closed connection without accepting message");
312 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
315 } catch (SMTPException e) {
316 if (accepted) return true;
317 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
318 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
319 Log.warn(SMTP.Outgoing.class, e);
320 if (e.code >= 500 && e.code <= 599) {
322 attempt(m.bounce("unable to deliver: " + e), true);
323 } catch (Exception ex) {
324 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
325 Log.error(SMTP.Outgoing.class, ex);
330 } catch (Exception e) {
331 if (accepted) return true;
332 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
333 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
334 Log.warn(SMTP.Outgoing.class, e);
335 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
338 if (conn != null) conn.close();
343 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
344 private static int serials = 1;
345 private int serial = serials++;
346 private Mailbox.Iterator it;
349 synchronized(Outgoing.class) {
355 int count = spool.count(Query.all());
356 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
359 boolean good = false;
360 synchronized(Outgoing.class) {
361 it = spool.iterator();
362 OUTER: for(; it.next(); ) {
363 for(Outgoing o : threads)
364 if (o!=this && o.it != null && o.it.uid()==it.uid())
372 if (attempt(it.cur())) it.delete();
373 } catch (Exception e) {
374 Log.error(SMTP.Outgoing.class, e);
376 Log.info(this, "sleeping for 3s...");
379 } catch (Exception e) {
380 //if (e instanceof InterruptedException) throw e;
381 Log.error(SMTP.Outgoing.class, e);
383 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
390 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
393 synchronized(Outgoing.class) {
394 Outgoing.class.wait(5 * 60 * 1000);
397 } catch (InterruptedException e) { Log.warn(this, e); }
401 public static InetAddress[] getMailExchangerIPs(String hostName) {
404 Hashtable env = new Hashtable();
405 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
406 DirContext ictx = new InitialDirContext(env);
407 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
408 Attribute attr = attrs.get("MX");
410 ret = new InetAddress[1];
412 ret[0] = InetAddress.getByName(hostName);
413 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
415 } catch (UnknownHostException uhe) {
416 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
417 return new InetAddress[0];
420 ret = new InetAddress[attr.size()];
421 NamingEnumeration ne = attr.getAll();
422 for(int i=0; ne.hasMore();) {
423 String mx = (String)ne.next();
424 // FIXME we should be sorting here
425 mx = mx.substring(mx.indexOf(" ") + 1);
426 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
427 InetAddress ia = InetAddress.getByName(mx);
428 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
432 } catch (Exception e) {
433 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
434 Log.warn(SMTP.class, e);
435 return new InetAddress[0];