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.
6 import org.ibex.mail.target.*;
7 import org.ibex.util.*;
14 import javax.naming.*;
15 import javax.naming.directory.*;
18 // RFC2554: SMTP Service Extension for Authentication
19 // - did not implement section 5, though
20 // RFC4616: SASL PLAIN
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
26 // FIXME: logging: current logging sucks
27 // FIXME: loop prevention
28 // FIXME: probably need some throttling on outbound mail
30 // FEATURE: public static boolean validate(Address a)
31 // FEATURE: rate-limiting
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
41 public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
42 public static final int numOutgoingThreads = 5;
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
47 public static final Graylist graylist =
48 new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite");
50 public static final Whitelist whitelist =
51 new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite");
53 public static final int MAX_MESSAGE_SIZE =
54 Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
56 private static final Mailbox spool =
57 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
60 for(int i=0; i<numOutgoingThreads; i++)
61 new Outgoing().start();
64 public static void enqueue(Message m) throws IOException {
65 if (!m.envelopeTo.isLocal()) Outgoing.enqueue(m);
66 else Target.root.accept(m);
69 public static class SMTPException extends MailException {
72 public SMTPException(String s) {
74 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
75 message = s.substring(s.indexOf(' ')+1);
76 } catch (NumberFormatException nfe) {
81 public String toString() { return "SMTP " + code + ": " + message; }
82 public String getMessage() { return toString(); }
85 // Server //////////////////////////////////////////////////////////////////////////////
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());
93 Vector to = new Vector();
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);
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);
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"
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");
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");
139 conn.println("551 sorry, " + addr + " is not on this machine");
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");
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");
158 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
160 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
164 conn.println("354 Enter message, ending with \".\" on a line by itself");
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");
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");
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));
189 String body = buf.toString();
191 for(int i=0; i<to.size(); i++) {
192 m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
195 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
196 conn.println("250 message accepted");
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);
206 } else { conn.println("500 unrecognized command"); }
207 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
212 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
214 public static class Outgoing extends Thread {
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");
222 for(int i=0; i<traces.length(); i++)
223 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
225 if (lines > 100) { // required by rfc
226 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
230 synchronized(Outgoing.class) {
231 spool.insert(m, Mailbox.Flag.defaultFlags);
232 Outgoing.class.notifyAll();
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());
242 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
243 if (mx.length == 0) {
245 accept(m.bounce("could not resolve " + m.envelopeTo.host));
248 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
252 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
254 accept(m.bounce("could not send for 5 days"));
257 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
261 for(int i=0; i<mx.length; i++) {
262 //if (deadHosts.contains(mx[i])) continue;
263 if (attempt(m, mx[i])) { return true; }
268 private static void check(String s, Connection conn) {
270 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
271 if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
273 private static boolean attempt(final Message m, final InetAddress mx) {
274 boolean accepted = false;
275 Connection conn = null;
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
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);
290 if (m.envelopeFrom==null) {
291 Log.warn("", "MAIL FROM:<>");
292 conn.println("MAIL FROM:<>"); check(conn.readln(), conn);
294 Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
295 conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">"); check(conn.readln(), conn);
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(".");
308 stream = m.getBody().getStream();
309 for(String s = stream.readln(); s!=null; s=stream.readln()) {
310 if (s.startsWith(".")) conn.print(".");
314 String resp = conn.readln();
316 throw new SMTPException("server " + mx + " closed connection without accepting message");
318 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
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) {
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);
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());
344 if (conn != null) conn.close();
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;
355 synchronized(Outgoing.class) {
361 int count = spool.count(Query.all());
362 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
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())
378 if (attempt(it.cur())) it.delete();
379 } catch (Exception e) {
380 Log.error(SMTP.Outgoing.class, e);
382 Log.info(this, "sleeping for 3s...");
385 } catch (Exception e) {
386 //if (e instanceof InterruptedException) throw e;
387 Log.error(SMTP.Outgoing.class, e);
389 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
396 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
399 synchronized(Outgoing.class) {
400 Outgoing.class.wait(5 * 60 * 1000);
403 } catch (InterruptedException e) { Log.warn(this, e); }
407 public static InetAddress[] getMailExchangerIPs(String hostName) {
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");
416 ret = new InetAddress[1];
418 ret[0] = InetAddress.getByName(hostName);
419 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
421 } catch (UnknownHostException uhe) {
422 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
423 return new InetAddress[0];
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;
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];