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 // Don't perform SAV; discouraged here
203 // http://blog.fastmail.fm/2007/12/05/sending-email-servers-best-practice/
204 } else if (c.startsWith("RCPT TO:")) {
205 // some clients are broken and put RCPT first; we will tolerate this
206 command = command.substring(8).trim();
207 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
208 Address addr = new Address(command);
209 if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
210 conn.println("250 you are connected locally, so I will let you send");
212 if (!whitelist.isWhitelisted(addr))
213 whitelist.addWhitelist(addr);
214 } else if (authenticatedAs!=null) {
215 conn.println("250 you are authenticated as "+authenticatedAs+", so I will let you send");
217 if (!whitelist.isWhitelisted(addr))
218 whitelist.addWhitelist(addr);
219 } else if (addr.isLocal()) {
221 conn.println("536 sorry, limit on 3 RCPT TO's per DATA");
223 // FEATURE: should check the address further and give 550 if undeliverable
224 conn.println("250 " + addr + " is on this machine; I will deliver it");
228 conn.println("535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
229 Log.warn("","535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
231 if (failedRcptCount > 3) {
237 } else if (c.startsWith("DATA")) {
238 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
239 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
240 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress() && authenticatedAs==null) {
241 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
242 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
243 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
244 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
245 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
248 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
249 graylist.addWhitelist(conn.getRemoteAddress());
250 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
251 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
253 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
255 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
259 conn.println("354 Enter message, ending with \".\" on a line by itself");
263 // FIXME: deal with messages larger than memory here?
264 StringBuffer buf = new StringBuffer();
265 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
266 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
268 // FIXME: this is leaking BCC addrs
269 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
270 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
272 // FIXME: some sort of stream transformer here?
274 String s = conn.readln();
275 if (s == null) throw new RuntimeException("connection closed");
276 if (s.equals(".")) break;
277 if (s.startsWith(".")) s = s.substring(1);
278 buf.append(s + "\r\n");
279 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE && (from+"").indexOf("paperless")==-1) {
280 Log.error("**"+conn.getRemoteAddress()+"**",
281 "sorry, this mail server only accepts messages of less than " +
282 ByteSize.toString(MAX_MESSAGE_SIZE));
283 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
284 ByteSize.toString(MAX_MESSAGE_SIZE));
287 String message = buf.toString();
289 for(int i=0; i<to.size(); i++)
290 enqueue(m = Message.newMessage(Fountain.Util.create(message)).withEnvelope(from, (Address)to.elementAt(i)));
291 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
292 conn.println("250 message accepted");
294 from = null; to = new Vector();
295 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
296 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
297 } catch (Script.Later.LaterException le) { conn.println("453 try again later");
298 } catch (Script.Reject.RejectException re) {
299 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
300 conn.println("501 " + re.reason);
302 } else { conn.println("500 unrecognized command"); }
303 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
308 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
310 public static class Outgoing extends Thread {
312 private static final HashMap deadHosts = new HashMap();
313 public static void enqueue(Message m) throws IOException {
314 if (m == null) { Log.warn(Outgoing.class, "attempted to enqueue(null)"); return; }
315 String traces = m.headers.get("Received");
318 for(int i=0; i<traces.length(); i++)
319 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
321 if (lines > 100) { // required by rfc
322 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
326 synchronized(Outgoing.class) {
327 spool.insert(m, Mailbox.Flag.defaultFlags);
328 Outgoing.class.notifyAll();
332 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
333 public static boolean attempt(Message m, boolean noBounces) throws IOException {
334 if (m.envelopeTo == null) {
335 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
338 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
339 if (mx.length == 0) {
341 enqueue(m.bounce("could not resolve " + m.envelopeTo.host));
344 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
348 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
350 enqueue(m.bounce("could not send for 5 days"));
353 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
357 for(int i=0; i<mx.length; i++) {
358 //if (deadHosts.contains(mx[i])) continue;
359 if (attempt(m, mx[i])) return true;
364 private static void check(String s, Connection conn) {
366 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
367 //if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
368 if (!s.startsWith("2")&&!s.startsWith("3")) throw new SMTPException(s);
370 private static boolean attempt(final Message m, final InetAddress mx) {
371 boolean accepted = false;
372 Connection conn = null;
374 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
375 InetAddress localAddress = conn.getSocket().getLocalAddress();
376 String reverse = DNSUtil.reverseLookup(localAddress);
377 Log.info(SMTP.Outgoing.class,
378 "outbound connection to " + mx + " uses " + localAddress + " [reverse: " + reverse + "]");
379 InetAddress relookup = InetAddress.getByName(reverse);
380 if (!relookup.equals(localAddress))
381 Log.error(SMTP.Outgoing.class,
382 "Warning: local machine fails forward-confirmed-reverse; " +
383 reverse + " resolves to " + localAddress);
384 conn.setNewline("\r\n");
385 conn.setTimeout(60 * 1000);
386 check(conn.readln(), conn); // banner
388 conn.println("EHLO " + reverse);
389 check(conn.readln(), conn);
390 } catch (SMTPException smtpe) {
391 conn.println("HELO " + reverse);
392 check(conn.readln(), conn);
394 String envelopeFrom = m.envelopeFrom==null ? "" : m.envelopeFrom.toString();
395 conn.println("MAIL FROM:<" + envelopeFrom +">"); check(conn.readln(), conn);
396 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
397 conn.println("DATA"); check(conn.readln(), conn);
399 Headers head = new Headers(m.headers,
404 Stream stream = head.getStream();
405 for(String s = stream.readln(); s!=null; s=stream.readln()) {
406 if (s.startsWith(".")) conn.print(".");
410 stream = m.getBody().getStream();
411 for(String s = stream.readln(); s!=null; s=stream.readln()) {
412 if (s.startsWith(".")) conn.print(".");
416 String resp = conn.readln();
418 throw new SMTPException("server " + mx + " closed connection without accepting message");
420 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
423 } catch (SMTPException e) {
424 if (accepted) return true;
425 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
426 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
427 Log.warn(SMTP.Outgoing.class, e);
429 // FIXME: we should not be bouncing here!
430 if (e.code >= 500 && e.code <= 599) {
432 attempt(m.bounce("unable to deliver: " + e), true);
433 } catch (Exception ex) {
434 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
435 Log.error(SMTP.Outgoing.class, ex);
441 } catch (Exception e) {
442 if (accepted) return true;
443 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
444 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
445 Log.warn(SMTP.Outgoing.class, e);
446 //if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
449 if (conn != null) conn.close();
454 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
455 private static int serials = 1;
456 private int serial = serials++;
457 private Mailbox.Iterator it;
459 private static Map<String,Long> nextTry = Collections.synchronizedMap(new HashMap<String,Long>());
462 synchronized(Outgoing.class) {
468 int count = spool.count(Query.all());
469 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
472 boolean good = false;
473 synchronized(Outgoing.class) {
474 it = spool.iterator();
475 OUTER: for(; it.next(); ) {
476 for(Outgoing o : threads)
477 if (o!=this && o.it != null && o.it.uid()==it.uid())
485 String messageid = it.cur().messageid;
486 if (nextTry.get(messageid) == null || System.currentTimeMillis() > nextTry.get(messageid)) {
487 boolean ok = attempt(it.cur());
489 else nextTry.put(messageid, System.currentTimeMillis() + RETRY_TIME);
491 } catch (Exception e) {
492 Log.error(SMTP.Outgoing.class, e);
494 Log.info(this, "sleeping for 3s...");
497 } catch (Exception e) {
498 //if (e instanceof InterruptedException) throw e;
499 Log.error(SMTP.Outgoing.class, e);
501 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
508 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
511 synchronized(Outgoing.class) {
512 Outgoing.class.wait(5 * 60 * 1000);
515 } catch (InterruptedException e) { Log.warn(this, e); }
519 public static InetAddress[] getMailExchangerIPs(String hostName) {
522 Hashtable env = new Hashtable();
523 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
524 DirContext ictx = new InitialDirContext(env);
525 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
526 Attribute attr = attrs.get("MX");
528 ret = new InetAddress[1];
530 ret[0] = InetAddress.getByName(hostName);
531 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
533 } catch (UnknownHostException uhe) {
534 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
535 return new InetAddress[0];
538 ret = new InetAddress[attr.size()];
539 NamingEnumeration ne = attr.getAll();
540 for(int i=0; ne.hasMore();) {
541 String mx = (String)ne.next();
542 // FIXME we should be sorting here
543 mx = mx.substring(mx.indexOf(" ") + 1);
544 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
545 InetAddress ia = InetAddress.getByName(mx);
546 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
550 } catch (Exception e) {
551 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
552 Log.warn(SMTP.class, e);
553 return new InetAddress[0];