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) throws IOException {
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");
195 } else { conn.println("500 unrecognized command"); }
196 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
201 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
203 public static class Outgoing extends Thread {
205 private static final HashMap deadHosts = new HashMap();
206 public static void accept(Message m) throws IOException {
207 if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
208 String traces = m.headers.get("Received");
211 for(int i=0; i<traces.length(); i++)
212 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
214 if (lines > 100) { // required by rfc
215 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
219 synchronized(Outgoing.class) {
220 spool.insert(m, Mailbox.Flag.defaultFlags);
221 Outgoing.class.notifyAll();
225 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
226 public static boolean attempt(Message m, boolean noBounces) throws IOException {
227 if (m.envelopeTo == null) {
228 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
231 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
232 if (mx.length == 0) {
234 accept(m.bounce("could not resolve " + m.envelopeTo.host));
237 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
241 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
243 accept(m.bounce("could not send for 5 days"));
246 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
250 for(int i=0; i<mx.length; i++) {
251 //if (deadHosts.contains(mx[i])) continue;
252 if (attempt(m, mx[i])) { return true; }
257 private static void check(String s, Connection conn) {
259 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
260 if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
262 private static boolean attempt(final Message m, final InetAddress mx) {
263 boolean accepted = false;
264 Connection conn = null;
266 Log.note("connecting to " + mx + "...");
267 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
268 conn.setNewline("\r\n");
269 conn.setTimeout(60 * 1000);
270 Log.note(" connected");
271 check(conn.readln(), conn); // banner
273 conn.println("EHLO " + conn.vhost);
274 check(conn.readln(), conn);
275 } catch (SMTPException smtpe) {
276 conn.println("HELO " + conn.vhost);
277 check(conn.readln(), conn);
279 if (m.envelopeFrom==null) {
280 Log.warn("", "MAIL FROM:<>");
281 conn.println("MAIL FROM:<>"); check(conn.readln(), conn);
283 Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
284 conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">"); check(conn.readln(), conn);
286 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
287 conn.println("DATA"); check(conn.readln(), conn);
288 Headers head = m.headers;
289 head = head.remove("return-path");
290 head = head.remove("bcc");
291 Stream stream = head.getStream();
292 for(String s = stream.readln(); s!=null; s=stream.readln()) {
293 if (s.startsWith(".")) conn.print(".");
297 stream = m.getBody().getStream();
298 for(String s = stream.readln(); s!=null; s=stream.readln()) {
299 if (s.startsWith(".")) conn.print(".");
303 String resp = conn.readln();
305 throw new SMTPException("server " + mx + " closed connection without accepting message");
307 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
310 } catch (SMTPException e) {
311 if (accepted) return true;
312 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
313 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
314 Log.warn(SMTP.Outgoing.class, e);
315 if (e.code >= 500 && e.code <= 599) {
317 attempt(m.bounce("unable to deliver: " + e), true);
318 } catch (Exception ex) {
319 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
320 Log.error(SMTP.Outgoing.class, ex);
325 } catch (Exception e) {
326 if (accepted) return true;
327 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
328 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
329 Log.warn(SMTP.Outgoing.class, e);
330 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
333 if (conn != null) conn.close();
338 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
339 private static int serials = 1;
340 private int serial = serials++;
341 private Mailbox.Iterator it;
344 synchronized(Outgoing.class) {
350 int count = spool.count(Query.all());
351 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
354 boolean good = false;
355 synchronized(Outgoing.class) {
356 it = spool.iterator();
357 OUTER: for(; it.next(); ) {
358 for(Outgoing o : threads)
359 if (o!=this && o.it != null && o.it.uid()==it.uid())
367 if (attempt(it.cur())) it.delete();
368 } catch (Exception e) {
369 Log.error(SMTP.Outgoing.class, e);
371 Log.info(this, "sleeping for 3s...");
374 } catch (Exception e) {
375 //if (e instanceof InterruptedException) throw e;
376 Log.error(SMTP.Outgoing.class, e);
378 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
385 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
388 synchronized(Outgoing.class) {
389 Outgoing.class.wait(5 * 60 * 1000);
392 } catch (InterruptedException e) { Log.warn(this, e); }
396 public static InetAddress[] getMailExchangerIPs(String hostName) {
399 Hashtable env = new Hashtable();
400 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
401 DirContext ictx = new InitialDirContext(env);
402 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
403 Attribute attr = attrs.get("MX");
405 ret = new InetAddress[1];
407 ret[0] = InetAddress.getByName(hostName);
408 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
410 } catch (UnknownHostException uhe) {
411 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
412 return new InetAddress[0];
415 ret = new InetAddress[attr.size()];
416 NamingEnumeration ne = attr.getAll();
417 for(int i=0; ne.hasMore();) {
418 String mx = (String)ne.next();
419 // FIXME we should be sorting here
420 mx = mx.substring(mx.indexOf(" ") + 1);
421 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
422 InetAddress ia = InetAddress.getByName(mx);
423 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
427 } catch (Exception e) {
428 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
429 Log.warn(SMTP.class, e);
430 return new InetAddress[0];