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: infer messageid, date, if not present (?)
31 // FEATURE: exponential backoff on retry time?
32 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
33 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
34 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
35 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
38 public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
39 public static final int numOutgoingThreads = 5;
41 public static final int GRAYLIST_MINWAIT = 1000 * 60 * 60; // one hour
42 public static final int GRAYLIST_MAXWAIT = 1000 * 60 * 60 * 24 * 5; // five days
44 public static final Graylist graylist =
45 new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite");
47 public static final Whitelist whitelist =
48 new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite");
50 public static final int MAX_MESSAGE_SIZE =
51 Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
53 private static final Mailbox spool =
54 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
57 for(int i=0; i<numOutgoingThreads; i++)
58 new Outgoing().start();
61 public static void accept(Message m) throws IOException {
62 if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
63 else Target.root.accept(m);
66 public static class SMTPException extends MailException {
69 public SMTPException(String s) {
71 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
72 message = s.substring(s.indexOf(' ')+1);
73 } catch (NumberFormatException nfe) {
78 public String toString() { return "SMTP " + code + ": " + message; }
79 public String getMessage() { return toString(); }
82 // Server //////////////////////////////////////////////////////////////////////////////
84 public static class Server {
85 public void handleRequest(Connection conn) throws IOException {
86 conn.setTimeout(5 * 60 * 1000);
87 conn.setNewline("\r\n");
88 conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
90 Vector to = new Vector();
92 String remotehost = null;
93 for(String command = conn.readln(); ; command = conn.readln()) try {
94 if (command == null) return;
95 //Log.warn("**"+conn.getRemoteAddress()+"**", command);
96 String c = command.toUpperCase();
97 if (c.startsWith("HELO")) {
98 remotehost = c.substring(5).trim();
99 conn.println("250 HELO " + conn.vhost);
100 from = null; to = new Vector();
101 } else if (c.startsWith("EHLO")) {
102 remotehost = c.substring(5).trim();
103 conn.println("250 "+conn.vhost+" greets " + remotehost);
105 from = null; to = new Vector();
106 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
107 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
108 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
109 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
110 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
111 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
112 } else if (c.startsWith("MAIL FROM:")) {
113 command = command.substring(10).trim();
114 from = command.equals("<>") ? null : new Address(command);
115 conn.println("250 " + from + " is syntactically correct");
116 } else if (c.startsWith("RCPT TO:")) {
117 // some clients are broken and put RCPT first; we will tolerate this
118 command = command.substring(8).trim();
119 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
120 Address addr = new Address(command);
122 Log.warn("**"+conn.getRemoteAddress()+"**",
123 "addr.isLocal(): " + addr.isLocal() + "\n" +
124 "conn.getRemoteAddress().isLoopbackAddress(): " + conn.getRemoteAddress().isLoopbackAddress() + "\n" +
125 "johnw: " + (from!=null&&from.toString().indexOf("johnw")!=-1) + "\n"
128 if (addr.isLocal()) {
129 // FEATURE: should check the address further and give 550 if undeliverable
130 conn.println("250 " + addr + " is on this machine; I will deliver it");
132 } else if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
133 conn.println("250 you are connected locally, so I will let you send");
136 conn.println("551 sorry, " + addr + " is not on this machine");
139 } else if (c.startsWith("DATA")) {
140 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
141 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
142 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress()) {
143 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
144 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
145 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
146 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
147 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
150 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
151 graylist.addWhitelist(conn.getRemoteAddress());
152 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
153 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
155 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
157 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
161 conn.println("354 Enter message, ending with \".\" on a line by itself");
165 StringBuffer buf = new StringBuffer();
166 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
167 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
169 // FIXME: this is leaking BCC addrs
170 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
171 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
173 String s = conn.readln();
174 if (s == null) throw new RuntimeException("connection closed");
175 if (s.equals(".")) break;
176 if (s.startsWith(".")) s = s.substring(1);
177 buf.append(s + "\r\n");
178 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE) {
179 Log.error("**"+conn.getRemoteAddress()+"**",
180 "sorry, this mail server only accepts messages of less than " +
181 ByteSize.toString(MAX_MESSAGE_SIZE));
182 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
183 ByteSize.toString(MAX_MESSAGE_SIZE));
186 String body = buf.toString();
188 for(int i=0; i<to.size(); i++) {
189 m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
192 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
193 conn.println("250 message accepted");
195 from = null; to = new Vector();
196 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
197 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
198 } catch (Script.Later.LaterException le) { conn.println("453 try again later");
199 } catch (Script.Reject.RejectException re) {
200 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
201 conn.println("501 " + re.reason);
203 } else { conn.println("500 unrecognized command"); }
204 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
209 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
211 public static class Outgoing extends Thread {
213 private static final HashMap deadHosts = new HashMap();
214 public static void accept(Message m) throws IOException {
215 if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
216 String traces = m.headers.get("Received");
219 for(int i=0; i<traces.length(); i++)
220 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
222 if (lines > 100) { // required by rfc
223 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
227 synchronized(Outgoing.class) {
228 spool.insert(m, Mailbox.Flag.defaultFlags);
229 Outgoing.class.notifyAll();
233 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
234 public static boolean attempt(Message m, boolean noBounces) throws IOException {
235 if (m.envelopeTo == null) {
236 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
239 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
240 if (mx.length == 0) {
242 accept(m.bounce("could not resolve " + m.envelopeTo.host));
245 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
249 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
251 accept(m.bounce("could not send for 5 days"));
254 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
258 for(int i=0; i<mx.length; i++) {
259 //if (deadHosts.contains(mx[i])) continue;
260 if (attempt(m, mx[i])) { return true; }
265 private static void check(String s, Connection conn) {
267 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
268 if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
270 private static boolean attempt(final Message m, final InetAddress mx) {
271 boolean accepted = false;
272 Connection conn = null;
274 Log.note("connecting to " + mx + "...");
275 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
276 conn.setNewline("\r\n");
277 conn.setTimeout(60 * 1000);
278 Log.note(" connected");
279 check(conn.readln(), conn); // banner
281 conn.println("EHLO " + conn.vhost);
282 check(conn.readln(), conn);
283 } catch (SMTPException smtpe) {
284 conn.println("HELO " + conn.vhost);
285 check(conn.readln(), conn);
287 if (m.envelopeFrom==null) {
288 Log.warn("", "MAIL FROM:<>");
289 conn.println("MAIL FROM:<>"); check(conn.readln(), conn);
291 Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
292 conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">"); check(conn.readln(), conn);
294 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
295 conn.println("DATA"); check(conn.readln(), conn);
296 Headers head = m.headers;
297 head = head.remove("return-path");
298 head = head.remove("bcc");
299 Stream stream = head.getStream();
300 for(String s = stream.readln(); s!=null; s=stream.readln()) {
301 if (s.startsWith(".")) conn.print(".");
305 stream = m.getBody().getStream();
306 for(String s = stream.readln(); s!=null; s=stream.readln()) {
307 if (s.startsWith(".")) conn.print(".");
311 String resp = conn.readln();
313 throw new SMTPException("server " + mx + " closed connection without accepting message");
315 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
318 } catch (SMTPException e) {
319 if (accepted) return true;
320 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
321 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
322 Log.warn(SMTP.Outgoing.class, e);
323 if (e.code >= 500 && e.code <= 599) {
325 attempt(m.bounce("unable to deliver: " + e), true);
326 } catch (Exception ex) {
327 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
328 Log.error(SMTP.Outgoing.class, ex);
333 } catch (Exception e) {
334 if (accepted) return true;
335 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
336 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
337 Log.warn(SMTP.Outgoing.class, e);
338 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
341 if (conn != null) conn.close();
346 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
347 private static int serials = 1;
348 private int serial = serials++;
349 private Mailbox.Iterator it;
352 synchronized(Outgoing.class) {
358 int count = spool.count(Query.all());
359 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
362 boolean good = false;
363 synchronized(Outgoing.class) {
364 it = spool.iterator();
365 OUTER: for(; it.next(); ) {
366 for(Outgoing o : threads)
367 if (o!=this && o.it != null && o.it.uid()==it.uid())
375 if (attempt(it.cur())) it.delete();
376 } catch (Exception e) {
377 Log.error(SMTP.Outgoing.class, e);
379 Log.info(this, "sleeping for 3s...");
382 } catch (Exception e) {
383 //if (e instanceof InterruptedException) throw e;
384 Log.error(SMTP.Outgoing.class, e);
386 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
393 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
396 synchronized(Outgoing.class) {
397 Outgoing.class.wait(5 * 60 * 1000);
400 } catch (InterruptedException e) { Log.warn(this, e); }
404 public static InetAddress[] getMailExchangerIPs(String hostName) {
407 Hashtable env = new Hashtable();
408 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
409 DirContext ictx = new InitialDirContext(env);
410 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
411 Attribute attr = attrs.get("MX");
413 ret = new InetAddress[1];
415 ret[0] = InetAddress.getByName(hostName);
416 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
418 } catch (UnknownHostException uhe) {
419 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
420 return new InetAddress[0];
423 ret = new InetAddress[attr.size()];
424 NamingEnumeration ne = attr.getAll();
425 for(int i=0; ne.hasMore();) {
426 String mx = (String)ne.next();
427 // FIXME we should be sorting here
428 mx = mx.substring(mx.indexOf(" ") + 1);
429 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
430 InetAddress ia = InetAddress.getByName(mx);
431 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
435 } catch (Exception e) {
436 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
437 Log.warn(SMTP.class, e);
438 return new InetAddress[0];