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 String authenticatedAs = null;
97 for(String command = conn.readln(); ; command = conn.readln()) try {
98 if (command == null) return;
99 Log.warn("**"+conn.getRemoteAddress()+"**", command);
100 String c = command.toUpperCase();
101 if (c.startsWith("HELO")) {
102 remotehost = c.substring(5).trim();
103 conn.println("250 HELO " + conn.vhost);
104 from = null; to = new Vector();
105 } else if (c.startsWith("EHLO")) {
106 remotehost = c.substring(5).trim();
107 conn.println("250-"+conn.vhost);
108 //conn.println("250-AUTH");
109 conn.println("250-AUTH PLAIN");
110 //conn.println("250-STARTTLS");
111 conn.println("250 HELP");
113 from = null; to = new Vector();
114 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
115 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
116 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
117 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
118 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
119 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
120 } else if (c.startsWith("STARTTLS")) {
121 conn.println("220 starting TLS...");
123 conn = conn.negotiateSSL(true);
124 from = null; to = new Vector();
125 } else if (c.startsWith("AUTH")) {
126 if (authenticatedAs != null) {
127 conn.println("503 you are already authenticated; you must reconnect to reauth");
129 String mechanism = command.substring(4).trim();
131 if (mechanism.indexOf(' ')!=-1) {
132 rest = mechanism.substring(mechanism.indexOf(' ')+1).trim();
133 mechanism = mechanism.substring(0, mechanism.indexOf(' '));
135 if (mechanism.equals("PLAIN")) {
136 // 538 Encryption required for requested authentication mechanism?
137 byte[] bytes = Encode.fromBase64(rest);
138 String authenticateUser = null;
139 String authorizeUser = null;
140 String password = null;
142 for(int i=0; i<=bytes.length; i++) {
143 if (i<bytes.length && bytes[i]!=0) continue;
144 String result = new String(bytes, start, i-start, "UTF-8");
145 if (authenticateUser==null) authenticateUser = result;
146 else if (authorizeUser==null) authorizeUser = result;
147 else if (password==null) password = result;
150 // FIXME: be smarter here
151 if (Main.auth.login(authorizeUser, password)!=null)
152 authenticatedAs = authenticateUser;
153 conn.println("235 Authentication successful");
155 } else if (mechanism.equals("CRAM-MD5")) {
157 conn.println("334 "+challenge);
158 String resp = conn.readln();
159 if (resp.equals("*")) {
160 conn.println("501 client requested AUTH cancellation");
162 } else if (mechanism.equals("ANONYMOUS")) {
163 } else if (mechanism.equals("EXTERNAL")) {
164 } else if (mechanism.equals("DIGEST-MD5")) {
167 conn.println("504 unrecognized authentication type");
169 // on success, reset to initial state; client will EHLO again
170 from = null; to = new Vector();
172 } else if (c.startsWith("MAIL FROM:")) {
173 command = command.substring(10).trim();
174 from = command.equals("<>") ? null : new Address(command);
175 conn.println("250 " + from + " is syntactically correct");
176 } else if (c.startsWith("RCPT TO:")) {
177 // some clients are broken and put RCPT first; we will tolerate this
178 command = command.substring(8).trim();
179 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
180 Address addr = new Address(command);
181 if (addr.isLocal()) {
182 // FEATURE: should check the address further and give 550 if undeliverable
183 conn.println("250 " + addr + " is on this machine; I will deliver it");
185 } else if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
186 conn.println("250 you are connected locally, so I will let you send");
188 whitelist.addWhitelist(addr);
189 } else if (authenticatedAs!=null) {
190 conn.println("250 you are authenticated as "+authenticatedAs+", so I will let you send");
192 whitelist.addWhitelist(addr);
194 conn.println("535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
195 Log.warn("","535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
198 } else if (c.startsWith("DATA")) {
199 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
200 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
201 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress() && authenticatedAs==null) {
202 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
203 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
204 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
205 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
206 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
209 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
210 graylist.addWhitelist(conn.getRemoteAddress());
211 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
212 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
214 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
216 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
220 conn.println("354 Enter message, ending with \".\" on a line by itself");
224 // FIXME: deal with messages larger than memory here?
225 StringBuffer buf = new StringBuffer();
226 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
227 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
229 // FIXME: this is leaking BCC addrs
230 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
231 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
233 // FIXME: some sort of stream transformer here?
235 String s = conn.readln();
236 if (s == null) throw new RuntimeException("connection closed");
237 if (s.equals(".")) break;
238 if (s.startsWith(".")) s = s.substring(1);
239 buf.append(s + "\r\n");
240 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE) {
241 Log.error("**"+conn.getRemoteAddress()+"**",
242 "sorry, this mail server only accepts messages of less than " +
243 ByteSize.toString(MAX_MESSAGE_SIZE));
244 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
245 ByteSize.toString(MAX_MESSAGE_SIZE));
248 String body = buf.toString();
250 for(int i=0; i<to.size(); i++) {
251 m = Message.newMessage(Fountain.Util.create(body), from, (Address)to.elementAt(i));
254 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
255 conn.println("250 message accepted");
257 from = null; to = new Vector();
258 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
259 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
260 } catch (Script.Later.LaterException le) { conn.println("453 try again later");
261 } catch (Script.Reject.RejectException re) {
262 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
263 conn.println("501 " + re.reason);
265 } else { conn.println("500 unrecognized command"); }
266 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
271 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
273 public static class Outgoing extends Thread {
275 private static final HashMap deadHosts = new HashMap();
276 public static void enqueue(Message m) throws IOException {
277 if (m == null) { Log.warn(Outgoing.class, "attempted to enqueue(null)"); return; }
278 String traces = m.headers.get("Received");
281 for(int i=0; i<traces.length(); i++)
282 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
284 if (lines > 100) { // required by rfc
285 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
289 synchronized(Outgoing.class) {
290 spool.insert(m, Mailbox.Flag.defaultFlags);
291 Outgoing.class.notifyAll();
295 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
296 public static boolean attempt(Message m, boolean noBounces) throws IOException {
297 if (m.envelopeTo == null) {
298 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
301 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
302 if (mx.length == 0) {
304 enqueue(m.bounce("could not resolve " + m.envelopeTo.host));
307 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
311 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
313 enqueue(m.bounce("could not send for 5 days"));
316 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
320 for(int i=0; i<mx.length; i++) {
321 //if (deadHosts.contains(mx[i])) continue;
322 if (attempt(m, mx[i])) { return true; }
327 private static void check(String s, Connection conn) {
329 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
330 if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
332 private static boolean attempt(final Message m, final InetAddress mx) {
333 boolean accepted = false;
334 Connection conn = null;
336 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
337 conn.setNewline("\r\n");
338 conn.setTimeout(60 * 1000);
339 check(conn.readln(), conn); // banner
341 conn.println("EHLO " + conn.vhost);
342 check(conn.readln(), conn);
343 } catch (SMTPException smtpe) {
344 conn.println("HELO " + conn.vhost);
345 check(conn.readln(), conn);
347 String envelopeFrom = m.envelopeFrom==null ? "" : m.envelopeFrom.toString();
348 conn.println("MAIL FROM:<" + envelopeFrom +">"); check(conn.readln(), conn);
349 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
350 conn.println("DATA"); check(conn.readln(), conn);
352 Headers head = new Headers(m.headers,
357 Stream stream = head.getStream();
358 for(String s = stream.readln(); s!=null; s=stream.readln()) {
359 if (s.startsWith(".")) conn.print(".");
363 stream = m.getBody().getStream();
364 for(String s = stream.readln(); s!=null; s=stream.readln()) {
365 if (s.startsWith(".")) conn.print(".");
369 String resp = conn.readln();
371 throw new SMTPException("server " + mx + " closed connection without accepting message");
373 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
376 } catch (SMTPException e) {
377 if (accepted) return true;
378 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
379 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
380 Log.warn(SMTP.Outgoing.class, e);
381 if (e.code >= 500 && e.code <= 599) {
383 attempt(m.bounce("unable to deliver: " + e), true);
384 } catch (Exception ex) {
385 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
386 Log.error(SMTP.Outgoing.class, ex);
391 } catch (Exception e) {
392 if (accepted) return true;
393 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
394 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
395 Log.warn(SMTP.Outgoing.class, e);
396 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
399 if (conn != null) conn.close();
404 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
405 private static int serials = 1;
406 private int serial = serials++;
407 private Mailbox.Iterator it;
410 synchronized(Outgoing.class) {
416 int count = spool.count(Query.all());
417 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
420 boolean good = false;
421 synchronized(Outgoing.class) {
422 it = spool.iterator();
423 OUTER: for(; it.next(); ) {
424 for(Outgoing o : threads)
425 if (o!=this && o.it != null && o.it.uid()==it.uid())
433 if (attempt(it.cur())) it.delete();
434 } catch (Exception e) {
435 Log.error(SMTP.Outgoing.class, e);
437 Log.info(this, "sleeping for 3s...");
440 } catch (Exception e) {
441 //if (e instanceof InterruptedException) throw e;
442 Log.error(SMTP.Outgoing.class, e);
444 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
451 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
454 synchronized(Outgoing.class) {
455 Outgoing.class.wait(5 * 60 * 1000);
458 } catch (InterruptedException e) { Log.warn(this, e); }
462 public static InetAddress[] getMailExchangerIPs(String hostName) {
465 Hashtable env = new Hashtable();
466 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
467 DirContext ictx = new InitialDirContext(env);
468 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
469 Attribute attr = attrs.get("MX");
471 ret = new InetAddress[1];
473 ret[0] = InetAddress.getByName(hostName);
474 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
476 } catch (UnknownHostException uhe) {
477 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
478 return new InetAddress[0];
481 ret = new InetAddress[attr.size()];
482 NamingEnumeration ne = attr.getAll();
483 for(int i=0; ne.hasMore();) {
484 String mx = (String)ne.next();
485 // FIXME we should be sorting here
486 mx = mx.substring(mx.indexOf(" ") + 1);
487 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
488 InetAddress ia = InetAddress.getByName(mx);
489 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
493 } catch (Exception e) {
494 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
495 Log.warn(SMTP.class, e);
496 return new InetAddress[0];