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.*;
17 // FIXME: inbound throttling/ratelimiting
19 // "Address enumeration detection" -- notice when it looks like somebody
20 // is trying a raft of addresses.
23 // RFC2554: SMTP Service Extension for Authentication
24 // - did not implement section 5, though
25 // RFC4616: SASL PLAIN
27 // Note: we can't actually use status codes for feedback if we accept
28 // multiple destination addresses... a failure on one and success on
31 // FIXME: logging: current logging sucks
32 // FIXME: loop prevention
33 // FIXME: probably need some throttling on outbound mail
35 // FEATURE: public static boolean validate(Address a)
36 // FEATURE: rate-limiting
38 // FEATURE: infer messageid, date, if not present (?)
39 // FEATURE: exponential backoff on retry time?
40 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
41 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
42 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
43 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
46 public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
47 public static final int numOutgoingThreads = 5;
49 public static final int GRAYLIST_MINWAIT = 1000 * 60 * 60; // one hour
50 public static final int GRAYLIST_MAXWAIT = 1000 * 60 * 60 * 24 * 5; // five days
52 public static final Graylist graylist;
53 public static final Whitelist whitelist;
56 graylist = new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite");
57 whitelist = new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite");
58 } catch (Exception e) {
59 throw new RuntimeException(e);
63 public static final int MAX_MESSAGE_SIZE =
64 Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
66 private static final Mailbox spool =
67 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true).getMailbox();
70 for(int i=0; i<numOutgoingThreads; i++)
71 new Outgoing().start();
74 public static void enqueue(Message m) throws IOException {
75 if (!m.envelopeTo.isLocal()) Outgoing.enqueue(m);
76 else Target.root.accept(m);
79 public static class SMTPException extends MailException {
82 public SMTPException(String s) {
84 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
85 message = s.substring(s.indexOf(' ')+1);
86 } catch (NumberFormatException nfe) {
91 public String toString() { return "SMTP " + code + ": " + message; }
92 public String getMessage() { return toString(); }
95 // Server //////////////////////////////////////////////////////////////////////////////
97 public static class Server {
98 public void handleRequest(Connection conn) throws IOException {
99 conn.setTimeout(5 * 60 * 1000);
100 conn.setNewline("\r\n");
101 conn.println("220 " + conn.vhost + " ESMTP " + this.getClass().getName());
103 Vector to = new Vector();
104 boolean ehlo = false;
105 String remotehost = null;
106 String authenticatedAs = null;
107 int failedRcptCount = 0;
108 for(String command = conn.readln(); ; command = conn.readln()) try {
109 if (command == null) return;
110 Log.warn("**"+conn.getRemoteAddress()+"**", command);
111 String c = command.toUpperCase();
112 if (c.startsWith("HELO")) {
113 remotehost = c.substring(5).trim();
114 conn.println("250 HELO " + conn.vhost);
115 from = null; to = new Vector();
116 } else if (c.startsWith("EHLO")) {
117 remotehost = c.substring(5).trim();
118 conn.println("250-"+conn.vhost);
119 //conn.println("250-AUTH");
120 conn.println("250-AUTH PLAIN");
121 //conn.println("250-STARTTLS");
122 conn.println("250 HELP");
124 from = null; to = new Vector();
125 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
126 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
127 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
128 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
129 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
130 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
131 } else if (c.startsWith("STARTTLS")) {
132 conn.println("220 starting TLS...");
134 conn = conn.negotiateSSL(true);
135 from = null; to = new Vector();
136 } else if (c.startsWith("AUTH")) {
137 if (authenticatedAs != null) {
138 conn.println("503 you are already authenticated; you must reconnect to reauth");
140 String mechanism = command.substring(4).trim();
142 if (mechanism.indexOf(' ')!=-1) {
143 rest = mechanism.substring(mechanism.indexOf(' ')+1).trim();
144 mechanism = mechanism.substring(0, mechanism.indexOf(' '));
146 if (mechanism.equals("PLAIN")) {
147 // 538 Encryption required for requested authentication mechanism?
148 byte[] bytes = Encode.fromBase64(rest);
149 String authenticateUser = null;
150 String authorizeUser = null;
151 String password = null;
153 for(int i=0; i<=bytes.length; i++) {
154 if (i<bytes.length && bytes[i]!=0) continue;
155 String result = new String(bytes, start, i-start, "UTF-8");
156 if (authenticateUser==null) authenticateUser = result;
157 else if (authorizeUser==null) authorizeUser = result;
158 else if (password==null) password = result;
161 // FIXME: be smarter here
162 if (Main.auth.login(authorizeUser, password)!=null)
163 authenticatedAs = authenticateUser;
164 conn.println("235 Authentication successful");
166 } else if (mechanism.equals("CRAM-MD5")) {
168 conn.println("334 "+challenge);
169 String resp = conn.readln();
170 if (resp.equals("*")) {
171 conn.println("501 client requested AUTH cancellation");
173 } else if (mechanism.equals("ANONYMOUS")) {
174 } else if (mechanism.equals("EXTERNAL")) {
175 } else if (mechanism.equals("DIGEST-MD5")) {
178 conn.println("504 unrecognized authentication type");
180 // on success, reset to initial state; client will EHLO again
181 from = null; to = new Vector();
183 } else if (c.startsWith("MAIL FROM:")) {
184 command = command.substring(10).trim();
185 from = command.equals("<>") ? null : new Address(command);
186 conn.println("250 " + from + " is syntactically correct");
187 // FEATURE: perform SMTP validation on the address, reject if invalid
188 } else if (c.startsWith("RCPT TO:")) {
189 // some clients are broken and put RCPT first; we will tolerate this
190 command = command.substring(8).trim();
191 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
192 Address addr = new Address(command);
193 if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
194 conn.println("250 you are connected locally, so I will let you send");
196 if (!whitelist.isWhitelisted(addr))
197 whitelist.addWhitelist(addr);
198 } else if (authenticatedAs!=null) {
199 conn.println("250 you are authenticated as "+authenticatedAs+", so I will let you send");
201 if (!whitelist.isWhitelisted(addr))
202 whitelist.addWhitelist(addr);
203 } else if (addr.isLocal()) {
205 conn.println("536 sorry, limit on 3 RCPT TO's per DATA");
207 // FEATURE: should check the address further and give 550 if undeliverable
208 conn.println("250 " + addr + " is on this machine; I will deliver it");
212 conn.println("535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
213 Log.warn("","535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
215 if (failedRcptCount > 3) {
221 } else if (c.startsWith("DATA")) {
222 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
223 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
224 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress() && authenticatedAs==null) {
225 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
226 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
227 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
228 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
229 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
232 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
233 graylist.addWhitelist(conn.getRemoteAddress());
234 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
235 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
237 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
239 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
243 conn.println("354 Enter message, ending with \".\" on a line by itself");
247 // FIXME: deal with messages larger than memory here?
248 StringBuffer buf = new StringBuffer();
249 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
250 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
252 // FIXME: this is leaking BCC addrs
253 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
254 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
256 // FIXME: some sort of stream transformer here?
258 String s = conn.readln();
259 if (s == null) throw new RuntimeException("connection closed");
260 if (s.equals(".")) break;
261 if (s.startsWith(".")) s = s.substring(1);
262 buf.append(s + "\r\n");
263 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE && (from+"").indexOf("paperless")==-1) {
264 Log.error("**"+conn.getRemoteAddress()+"**",
265 "sorry, this mail server only accepts messages of less than " +
266 ByteSize.toString(MAX_MESSAGE_SIZE));
267 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
268 ByteSize.toString(MAX_MESSAGE_SIZE));
271 String message = buf.toString();
273 for(int i=0; i<to.size(); i++)
274 enqueue(m = Message.newMessage(Fountain.Util.create(message)).withEnvelope(from, (Address)to.elementAt(i)));
275 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
276 conn.println("250 message accepted");
278 from = null; to = new Vector();
279 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
280 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
281 } catch (Script.Later.LaterException le) { conn.println("453 try again later");
282 } catch (Script.Reject.RejectException re) {
283 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
284 conn.println("501 " + re.reason);
286 } else { conn.println("500 unrecognized command"); }
287 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
292 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
294 public static class Outgoing extends Thread {
296 private static final HashMap deadHosts = new HashMap();
297 public static void enqueue(Message m) throws IOException {
298 if (m == null) { Log.warn(Outgoing.class, "attempted to enqueue(null)"); return; }
299 String traces = m.headers.get("Received");
302 for(int i=0; i<traces.length(); i++)
303 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
305 if (lines > 100) { // required by rfc
306 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
310 synchronized(Outgoing.class) {
311 spool.insert(m, Mailbox.Flag.defaultFlags);
312 Outgoing.class.notifyAll();
316 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
317 public static boolean attempt(Message m, boolean noBounces) throws IOException {
318 if (m.envelopeTo == null) {
319 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
322 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
323 if (mx.length == 0) {
325 enqueue(m.bounce("could not resolve " + m.envelopeTo.host));
328 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
332 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
334 enqueue(m.bounce("could not send for 5 days"));
337 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
341 for(int i=0; i<mx.length; i++) {
342 //if (deadHosts.contains(mx[i])) continue;
343 if (attempt(m, mx[i])) return true;
348 private static void check(String s, Connection conn) {
350 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
351 //if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
352 if (!s.startsWith("2")&&!s.startsWith("3")) throw new SMTPException(s);
354 private static boolean attempt(final Message m, final InetAddress mx) {
355 boolean accepted = false;
356 Connection conn = null;
358 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
359 conn.setNewline("\r\n");
360 conn.setTimeout(60 * 1000);
361 check(conn.readln(), conn); // banner
363 conn.println("EHLO " + conn.vhost);
364 check(conn.readln(), conn);
365 } catch (SMTPException smtpe) {
366 conn.println("HELO " + conn.vhost);
367 check(conn.readln(), conn);
369 String envelopeFrom = m.envelopeFrom==null ? "" : m.envelopeFrom.toString();
370 conn.println("MAIL FROM:<" + envelopeFrom +">"); check(conn.readln(), conn);
371 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
372 conn.println("DATA"); check(conn.readln(), conn);
374 Headers head = new Headers(m.headers,
379 Stream stream = head.getStream();
380 for(String s = stream.readln(); s!=null; s=stream.readln()) {
381 if (s.startsWith(".")) conn.print(".");
385 stream = m.getBody().getStream();
386 for(String s = stream.readln(); s!=null; s=stream.readln()) {
387 if (s.startsWith(".")) conn.print(".");
391 String resp = conn.readln();
393 throw new SMTPException("server " + mx + " closed connection without accepting message");
395 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
398 } catch (SMTPException e) {
399 if (accepted) return true;
400 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
401 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
402 Log.warn(SMTP.Outgoing.class, e);
404 // FIXME: we should not be bouncing here!
405 if (e.code >= 500 && e.code <= 599) {
407 attempt(m.bounce("unable to deliver: " + e), true);
408 } catch (Exception ex) {
409 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
410 Log.error(SMTP.Outgoing.class, ex);
416 } catch (Exception e) {
417 if (accepted) return true;
418 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
419 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
420 Log.warn(SMTP.Outgoing.class, e);
421 //if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
424 if (conn != null) conn.close();
429 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
430 private static int serials = 1;
431 private int serial = serials++;
432 private Mailbox.Iterator it;
435 synchronized(Outgoing.class) {
441 int count = spool.count(Query.all());
442 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
445 boolean good = false;
446 synchronized(Outgoing.class) {
447 it = spool.iterator();
448 OUTER: for(; it.next(); ) {
449 for(Outgoing o : threads)
450 if (o!=this && o.it != null && o.it.uid()==it.uid())
458 if (attempt(it.cur())) it.delete();
459 } catch (Exception e) {
460 Log.error(SMTP.Outgoing.class, e);
462 Log.info(this, "sleeping for 3s...");
465 } catch (Exception e) {
466 //if (e instanceof InterruptedException) throw e;
467 Log.error(SMTP.Outgoing.class, e);
469 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
476 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
479 synchronized(Outgoing.class) {
480 Outgoing.class.wait(5 * 60 * 1000);
483 } catch (InterruptedException e) { Log.warn(this, e); }
487 public static InetAddress[] getMailExchangerIPs(String hostName) {
490 Hashtable env = new Hashtable();
491 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
492 DirContext ictx = new InitialDirContext(env);
493 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
494 Attribute attr = attrs.get("MX");
496 ret = new InetAddress[1];
498 ret[0] = InetAddress.getByName(hostName);
499 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
501 } catch (UnknownHostException uhe) {
502 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
503 return new InetAddress[0];
506 ret = new InetAddress[attr.size()];
507 NamingEnumeration ne = attr.getAll();
508 for(int i=0; ne.hasMore();) {
509 String mx = (String)ne.next();
510 // FIXME we should be sorting here
511 mx = mx.substring(mx.indexOf(" ") + 1);
512 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
513 InetAddress ia = InetAddress.getByName(mx);
514 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
518 } catch (Exception e) {
519 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
520 Log.warn(SMTP.class, e);
521 return new InetAddress[0];