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 private static final SqliteMailbox allmail =
50 (SqliteMailbox)FileBasedMailbox
51 .getFileBasedMailbox("/afs/megacz.com/mail/user/megacz/allmail", false);
53 public static final int GRAYLIST_MINWAIT = 1000 * 60 * 60; // one hour
54 public static final int GRAYLIST_MAXWAIT = 1000 * 60 * 60 * 24 * 5; // five days
56 public static final int RETRY_TIME = 1000 * 60 * 30;
58 public static final Graylist graylist;
59 public static final Whitelist whitelist;
62 graylist = new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite");
63 whitelist = new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite");
64 } catch (Exception e) {
65 throw new RuntimeException(e);
69 public static final int MAX_MESSAGE_SIZE =
70 Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
72 private static final Mailbox spool =
73 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true).getMailbox();
76 for(int i=0; i<numOutgoingThreads; i++)
77 new Outgoing().start();
80 public static void enqueue(Message m) throws IOException {
81 if (!m.envelopeTo.isLocal()) Outgoing.enqueue(m);
85 } catch (Exception e) {
86 // FIXME incredibly gross hack
87 if (e.toString().indexOf("attempt to insert two messages with identical messageid")==-1)
88 Log.error(SMTP.class, e);
90 Target.root.accept(m);
94 public static class SMTPException extends MailException {
97 public SMTPException(String s) {
99 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
100 message = s.substring(s.indexOf(' ')+1);
101 } catch (NumberFormatException nfe) {
106 public String toString() { return "SMTP " + code + ": " + message; }
107 public String getMessage() { return toString(); }
110 // Server //////////////////////////////////////////////////////////////////////////////
112 public static class Server {
113 public void handleRequest(Connection conn) throws IOException {
114 conn.setTimeout(5 * 60 * 1000);
115 conn.setNewline("\r\n");
116 conn.println("220 " + conn.vhost + " ESMTP " + this.getClass().getName());
118 Vector to = new Vector();
119 boolean ehlo = false;
120 String remotehost = null;
121 String authenticatedAs = null;
122 int failedRcptCount = 0;
123 for(String command = conn.readln(); ; command = conn.readln()) try {
124 if (command == null) return;
125 Log.warn("**"+conn.getRemoteAddress()+"**", command);
126 String c = command.toUpperCase();
127 if (c.startsWith("HELO")) {
128 remotehost = c.substring(5).trim();
129 conn.println("250 HELO " + conn.vhost);
130 from = null; to = new Vector();
131 } else if (c.startsWith("EHLO")) {
132 remotehost = c.substring(5).trim();
133 conn.println("250-"+conn.vhost);
134 //conn.println("250-AUTH");
135 conn.println("250-AUTH PLAIN");
136 //conn.println("250-STARTTLS");
137 conn.println("250 HELP");
139 from = null; to = new Vector();
140 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
141 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
142 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
143 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
144 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
145 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
146 } else if (c.startsWith("STARTTLS")) {
147 conn.println("220 starting TLS...");
149 conn = conn.negotiateSSL(true);
150 from = null; to = new Vector();
151 } else if (c.startsWith("AUTH")) {
152 if (authenticatedAs != null) {
153 conn.println("503 you are already authenticated; you must reconnect to reauth");
155 String mechanism = command.substring(4).trim();
157 if (mechanism.indexOf(' ')!=-1) {
158 rest = mechanism.substring(mechanism.indexOf(' ')+1).trim();
159 mechanism = mechanism.substring(0, mechanism.indexOf(' '));
161 if (mechanism.equals("PLAIN")) {
162 // 538 Encryption required for requested authentication mechanism?
163 byte[] bytes = Encode.fromBase64(rest);
164 String authenticateUser = null;
165 String authorizeUser = null;
166 String password = null;
168 for(int i=0; i<=bytes.length; i++) {
169 if (i<bytes.length && bytes[i]!=0) continue;
170 String result = new String(bytes, start, i-start, "UTF-8");
171 if (authenticateUser==null) authenticateUser = result;
172 else if (authorizeUser==null) authorizeUser = result;
173 else if (password==null) password = result;
176 // FIXME: be smarter here
177 if (Main.auth.login(authorizeUser, password)!=null)
178 authenticatedAs = authenticateUser;
179 conn.println("235 Authentication successful");
181 } else if (mechanism.equals("CRAM-MD5")) {
183 conn.println("334 "+challenge);
184 String resp = conn.readln();
185 if (resp.equals("*")) {
186 conn.println("501 client requested AUTH cancellation");
188 } else if (mechanism.equals("ANONYMOUS")) {
189 } else if (mechanism.equals("EXTERNAL")) {
190 } else if (mechanism.equals("DIGEST-MD5")) {
193 conn.println("504 unrecognized authentication type");
195 // on success, reset to initial state; client will EHLO again
196 from = null; to = new Vector();
198 } else if (c.startsWith("MAIL FROM:")) {
199 command = command.substring(10).trim();
200 from = command.equals("<>") ? null : new Address(command);
201 conn.println("250 " + from + " is syntactically correct");
202 // FEATURE: perform SMTP validation on the address, reject if invalid
203 } else if (c.startsWith("RCPT TO:")) {
204 // some clients are broken and put RCPT first; we will tolerate this
205 command = command.substring(8).trim();
206 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
207 Address addr = new Address(command);
208 if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
209 conn.println("250 you are connected locally, so I will let you send");
211 if (!whitelist.isWhitelisted(addr))
212 whitelist.addWhitelist(addr);
213 } else if (authenticatedAs!=null) {
214 conn.println("250 you are authenticated as "+authenticatedAs+", so I will let you send");
216 if (!whitelist.isWhitelisted(addr))
217 whitelist.addWhitelist(addr);
218 } else if (addr.isLocal()) {
220 conn.println("536 sorry, limit on 3 RCPT TO's per DATA");
222 // FEATURE: should check the address further and give 550 if undeliverable
223 conn.println("250 " + addr + " is on this machine; I will deliver it");
227 conn.println("535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
228 Log.warn("","535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
230 if (failedRcptCount > 3) {
236 } else if (c.startsWith("DATA")) {
237 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
238 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
239 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress() && authenticatedAs==null) {
240 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
241 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
242 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
243 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
244 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
247 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
248 graylist.addWhitelist(conn.getRemoteAddress());
249 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
250 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
252 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
254 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
258 conn.println("354 Enter message, ending with \".\" on a line by itself");
262 // FIXME: deal with messages larger than memory here?
263 StringBuffer buf = new StringBuffer();
264 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
265 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
267 // FIXME: this is leaking BCC addrs
268 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
269 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
271 // FIXME: some sort of stream transformer here?
273 String s = conn.readln();
274 if (s == null) throw new RuntimeException("connection closed");
275 if (s.equals(".")) break;
276 if (s.startsWith(".")) s = s.substring(1);
277 buf.append(s + "\r\n");
278 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE && (from+"").indexOf("paperless")==-1) {
279 Log.error("**"+conn.getRemoteAddress()+"**",
280 "sorry, this mail server only accepts messages of less than " +
281 ByteSize.toString(MAX_MESSAGE_SIZE));
282 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
283 ByteSize.toString(MAX_MESSAGE_SIZE));
286 String message = buf.toString();
288 for(int i=0; i<to.size(); i++)
289 enqueue(m = Message.newMessage(Fountain.Util.create(message)).withEnvelope(from, (Address)to.elementAt(i)));
290 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
291 conn.println("250 message accepted");
293 from = null; to = new Vector();
294 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
295 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
296 } catch (Script.Later.LaterException le) { conn.println("453 try again later");
297 } catch (Script.Reject.RejectException re) {
298 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
299 conn.println("501 " + re.reason);
301 } else { conn.println("500 unrecognized command"); }
302 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
307 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
309 public static class Outgoing extends Thread {
311 private static final HashMap deadHosts = new HashMap();
312 public static void enqueue(Message m) throws IOException {
313 if (m == null) { Log.warn(Outgoing.class, "attempted to enqueue(null)"); return; }
314 String traces = m.headers.get("Received");
317 for(int i=0; i<traces.length(); i++)
318 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
320 if (lines > 100) { // required by rfc
321 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
325 synchronized(Outgoing.class) {
326 spool.insert(m, Mailbox.Flag.defaultFlags);
327 Outgoing.class.notifyAll();
331 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
332 public static boolean attempt(Message m, boolean noBounces) throws IOException {
333 if (m.envelopeTo == null) {
334 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
337 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
338 if (mx.length == 0) {
340 enqueue(m.bounce("could not resolve " + m.envelopeTo.host));
343 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
347 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
349 enqueue(m.bounce("could not send for 5 days"));
352 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
356 for(int i=0; i<mx.length; i++) {
357 //if (deadHosts.contains(mx[i])) continue;
358 if (attempt(m, mx[i])) return true;
363 private static void check(String s, Connection conn) {
365 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
366 //if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
367 if (!s.startsWith("2")&&!s.startsWith("3")) throw new SMTPException(s);
369 private static boolean attempt(final Message m, final InetAddress mx) {
370 boolean accepted = false;
371 Connection conn = null;
373 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
374 conn.setNewline("\r\n");
375 conn.setTimeout(60 * 1000);
376 check(conn.readln(), conn); // banner
378 conn.println("EHLO " + conn.vhost);
379 check(conn.readln(), conn);
380 } catch (SMTPException smtpe) {
381 conn.println("HELO " + conn.vhost);
382 check(conn.readln(), conn);
384 String envelopeFrom = m.envelopeFrom==null ? "" : m.envelopeFrom.toString();
385 conn.println("MAIL FROM:<" + envelopeFrom +">"); check(conn.readln(), conn);
386 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
387 conn.println("DATA"); check(conn.readln(), conn);
389 Headers head = new Headers(m.headers,
394 Stream stream = head.getStream();
395 for(String s = stream.readln(); s!=null; s=stream.readln()) {
396 if (s.startsWith(".")) conn.print(".");
400 stream = m.getBody().getStream();
401 for(String s = stream.readln(); s!=null; s=stream.readln()) {
402 if (s.startsWith(".")) conn.print(".");
406 String resp = conn.readln();
408 throw new SMTPException("server " + mx + " closed connection without accepting message");
410 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
413 } catch (SMTPException e) {
414 if (accepted) return true;
415 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
416 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
417 Log.warn(SMTP.Outgoing.class, e);
419 // FIXME: we should not be bouncing here!
420 if (e.code >= 500 && e.code <= 599) {
422 attempt(m.bounce("unable to deliver: " + e), true);
423 } catch (Exception ex) {
424 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
425 Log.error(SMTP.Outgoing.class, ex);
431 } catch (Exception e) {
432 if (accepted) return true;
433 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
434 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
435 Log.warn(SMTP.Outgoing.class, e);
436 //if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
439 if (conn != null) conn.close();
444 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
445 private static int serials = 1;
446 private int serial = serials++;
447 private Mailbox.Iterator it;
449 private static Map<String,Long> nextTry = Collections.synchronizedMap(new HashMap<String,Long>());
452 synchronized(Outgoing.class) {
458 int count = spool.count(Query.all());
459 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
462 boolean good = false;
463 synchronized(Outgoing.class) {
464 it = spool.iterator();
465 OUTER: for(; it.next(); ) {
466 for(Outgoing o : threads)
467 if (o!=this && o.it != null && o.it.uid()==it.uid())
475 String messageid = it.cur().messageid;
476 if (nextTry.get(messageid) == null || System.currentTimeMillis() > nextTry.get(messageid)) {
477 boolean ok = attempt(it.cur());
479 else nextTry.put(messageid, System.currentTimeMillis() + RETRY_TIME);
481 } catch (Exception e) {
482 Log.error(SMTP.Outgoing.class, e);
484 Log.info(this, "sleeping for 3s...");
487 } catch (Exception e) {
488 //if (e instanceof InterruptedException) throw e;
489 Log.error(SMTP.Outgoing.class, e);
491 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
498 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
501 synchronized(Outgoing.class) {
502 Outgoing.class.wait(5 * 60 * 1000);
505 } catch (InterruptedException e) { Log.warn(this, e); }
509 public static InetAddress[] getMailExchangerIPs(String hostName) {
512 Hashtable env = new Hashtable();
513 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
514 DirContext ictx = new InitialDirContext(env);
515 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
516 Attribute attr = attrs.get("MX");
518 ret = new InetAddress[1];
520 ret[0] = InetAddress.getByName(hostName);
521 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
523 } catch (UnknownHostException uhe) {
524 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
525 return new InetAddress[0];
528 ret = new InetAddress[attr.size()];
529 NamingEnumeration ne = attr.getAll();
530 for(int i=0; ne.hasMore();) {
531 String mx = (String)ne.next();
532 // FIXME we should be sorting here
533 mx = mx.substring(mx.indexOf(" ") + 1);
534 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
535 InetAddress ia = InetAddress.getByName(mx);
536 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
540 } catch (Exception e) {
541 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
542 Log.warn(SMTP.class, e);
543 return new InetAddress[0];