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 int MAX_MESSAGE_SIZE =
40 Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
42 private static final Mailbox spool =
43 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
46 for(int i=0; i<numOutgoingThreads; i++)
47 new Outgoing().start();
50 public static void accept(Message m) throws IOException {
51 if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
52 else Target.root.accept(m);
55 public static class SMTPException extends MailException {
58 public SMTPException(String s) {
60 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
61 message = s.substring(s.indexOf(' ')+1);
62 } catch (NumberFormatException nfe) {
67 public String toString() { return "SMTP " + code + ": " + message; }
68 public String getMessage() { return toString(); }
71 // Server //////////////////////////////////////////////////////////////////////////////
73 public static class Server {
74 public void handleRequest(Connection conn) {
75 conn.setTimeout(5 * 60 * 1000);
76 conn.setNewline("\r\n");
77 conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
79 Vector to = new Vector();
81 String remotehost = null;
82 for(String command = conn.readln(); ; command = conn.readln()) try {
83 if (command == null) return;
84 Log.warn("**"+conn.getRemoteAddress()+"**", command);
85 String c = command.toUpperCase();
86 if (c.startsWith("HELO")) {
87 remotehost = c.substring(5).trim();
88 conn.println("250 HELO " + conn.vhost);
89 from = null; to = new Vector();
90 } else if (c.startsWith("EHLO")) {
91 remotehost = c.substring(5).trim();
92 conn.println("250 "+conn.vhost+" greets " + remotehost);
94 from = null; to = new Vector();
95 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
96 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
97 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
98 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
99 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
100 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
101 } else if (c.startsWith("MAIL FROM:")) {
102 command = command.substring(10).trim();
103 from = command.equals("<>") ? null : new Address(command);
104 conn.println("250 " + from + " is syntactically correct");
105 } else if (c.startsWith("RCPT TO:")) {
106 // some clients are broken and put RCPT first; we will tolerate this
107 command = command.substring(8).trim();
108 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
109 Address addr = new Address(command);
111 Log.warn("**"+conn.getRemoteAddress()+"**",
112 "addr.isLocal(): " + addr.isLocal() + "\n" +
113 "conn.getRemoteAddress().isLoopbackAddress(): " + conn.getRemoteAddress().isLoopbackAddress() + "\n" +
114 "johnw: " + (from!=null&&from.toString().indexOf("johnw")!=-1) + "\n"
117 if (addr.isLocal()) {
118 // FEATURE: should check the address further and give 550 if undeliverable
119 conn.println("250 " + addr + " is on this machine; I will deliver it");
121 } else if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
122 conn.println("250 you are connected locally, so I will let you send");
125 conn.println("551 sorry, " + addr + " is not on this machine");
128 } else if (c.startsWith("DATA")) {
129 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
130 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
131 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress()) {
132 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
133 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
134 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
135 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
136 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
139 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
140 graylist.addWhitelist(conn.getRemoteAddress());
141 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
142 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
144 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
146 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
150 conn.println("354 Enter message, ending with \".\" on a line by itself");
154 StringBuffer buf = new StringBuffer();
155 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
156 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
158 // FIXME: this is leaking BCC addrs
159 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
160 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
162 String s = conn.readln();
163 if (s == null) throw new RuntimeException("connection closed");
164 if (s.equals(".")) break;
165 if (s.startsWith(".")) s = s.substring(1);
166 buf.append(s + "\r\n");
167 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE) {
168 Log.error("**"+conn.getRemoteAddress()+"**",
169 "sorry, this mail server only accepts messages of less than " +
170 ByteSize.toString(MAX_MESSAGE_SIZE));
171 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
172 ByteSize.toString(MAX_MESSAGE_SIZE));
175 String body = buf.toString();
177 for(int i=0; i<to.size(); i++) {
178 m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
181 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
182 conn.println("250 message accepted");
184 from = null; to = new Vector();
185 } catch (Reject.RejectException re) {
186 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
187 conn.println("501 " + re.reason);
188 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
189 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
190 } catch (Later.LaterException le) { conn.println("453 try again later");
191 } catch (IOException ioe) {
192 //conn.println("554 " + ioe.toString());
193 Log.error(this, ioe);
197 } else { conn.println("500 unrecognized command"); }
198 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
203 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
205 public static class Outgoing extends Thread {
207 private static final HashMap deadHosts = new HashMap();
208 public static void accept(Message m) throws IOException {
209 if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
210 String traces = m.headers.get("Received");
213 for(int i=0; i<traces.length(); i++)
214 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
216 if (lines > 100) { // required by rfc
217 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
221 synchronized(Outgoing.class) {
223 Outgoing.class.notifyAll();
227 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
228 public static boolean attempt(Message m, boolean noBounces) throws IOException {
229 if (m.envelopeTo == null) {
230 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
233 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
234 if (mx.length == 0) {
236 accept(m.bounce("could not resolve " + m.envelopeTo.host));
239 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
243 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
245 accept(m.bounce("could not send for 5 days"));
248 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
252 for(int i=0; i<mx.length; i++) {
253 //if (deadHosts.contains(mx[i])) continue;
254 if (attempt(m, mx[i])) { return true; }
259 private static void check(String s, Connection conn) {
261 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
262 if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
264 private static boolean attempt(final Message m, final InetAddress mx) {
265 boolean accepted = false;
266 Connection conn = null;
268 Log.note("connecting to " + mx + "...");
269 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
270 conn.setNewline("\r\n");
271 conn.setTimeout(60 * 1000);
272 Log.note(" connected");
273 check(conn.readln(), conn); // banner
275 conn.println("EHLO " + conn.vhost);
276 check(conn.readln(), conn);
277 } catch (SMTPException smtpe) {
278 conn.println("HELO " + conn.vhost);
279 check(conn.readln(), conn);
281 if (m.envelopeFrom==null) {
282 Log.warn("", "MAIL FROM:<>");
283 conn.println("MAIL FROM:<>"); check(conn.readln(), conn);
285 Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
286 conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">"); check(conn.readln(), conn);
288 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
289 conn.println("DATA"); check(conn.readln(), conn);
290 Headers head = m.headers;
291 head = head.remove("return-path");
292 head = head.remove("bcc");
293 Stream stream = head.getStream();
294 for(String s = stream.readln(); s!=null; s=stream.readln()) {
295 if (s.startsWith(".")) conn.print(".");
299 stream = m.getBody().getStream();
300 for(String s = stream.readln(); s!=null; s=stream.readln()) {
301 if (s.startsWith(".")) conn.print(".");
305 String resp = conn.readln();
307 throw new SMTPException("server " + mx + " closed connection without accepting message");
309 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
312 } catch (SMTPException e) {
313 if (accepted) return true;
314 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
315 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
316 Log.warn(SMTP.Outgoing.class, e);
317 if (e.code >= 500 && e.code <= 599) {
319 attempt(m.bounce("unable to deliver: " + e), true);
320 } catch (Exception ex) {
321 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
322 Log.error(SMTP.Outgoing.class, ex);
327 } catch (Exception e) {
328 if (accepted) return true;
329 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
330 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
331 Log.warn(SMTP.Outgoing.class, e);
332 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
335 if (conn != null) conn.close();
340 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
341 private static int serials = 1;
342 private int serial = serials++;
343 private Mailbox.Iterator it;
346 synchronized(Outgoing.class) {
352 int count = spool.count(Query.all());
353 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
356 boolean good = false;
357 synchronized(Outgoing.class) {
358 it = spool.iterator();
359 OUTER: for(; it.next(); ) {
360 for(Outgoing o : threads)
361 if (o!=this && o.it != null && o.it.uid()==it.uid())
369 if (attempt(it.cur())) it.delete();
370 } catch (Exception e) {
371 Log.error(SMTP.Outgoing.class, e);
373 Log.info(this, "sleeping for 3s...");
376 } catch (Exception e) {
377 //if (e instanceof InterruptedException) throw e;
378 Log.error(SMTP.Outgoing.class, e);
380 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
387 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
390 synchronized(Outgoing.class) {
391 Outgoing.class.wait(5 * 60 * 1000);
394 } catch (InterruptedException e) { Log.warn(this, e); }
398 public static InetAddress[] getMailExchangerIPs(String hostName) {
401 Hashtable env = new Hashtable();
402 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
403 DirContext ictx = new InitialDirContext(env);
404 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
405 Attribute attr = attrs.get("MX");
407 ret = new InetAddress[1];
409 ret[0] = InetAddress.getByName(hostName);
410 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
412 } catch (UnknownHostException uhe) {
413 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
414 return new InetAddress[0];
417 ret = new InetAddress[attr.size()];
418 NamingEnumeration ne = attr.getAll();
419 for(int i=0; ne.hasMore();) {
420 String mx = (String)ne.next();
421 // FIXME we should be sorting here
422 mx = mx.substring(mx.indexOf(" ") + 1);
423 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
424 InetAddress ia = InetAddress.getByName(mx);
425 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
429 } catch (Exception e) {
430 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
431 Log.warn(SMTP.class, e);
432 return new InetAddress[0];