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 Graylist graylist;
57 public static final Whitelist whitelist;
60 graylist = new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite");
61 whitelist = new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite");
62 } catch (Exception e) {
63 throw new RuntimeException(e);
67 public static final int MAX_MESSAGE_SIZE =
68 Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
70 private static final Mailbox spool =
71 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true).getMailbox();
74 for(int i=0; i<numOutgoingThreads; i++)
75 new Outgoing().start();
78 public static void enqueue(Message m) throws IOException {
79 if (!m.envelopeTo.isLocal()) Outgoing.enqueue(m);
83 } catch (Exception e) {
84 // FIXME incredibly gross hack
85 if (e.toString().indexOf("attempt to insert two messages with identical messageid")==-1)
86 Log.error(SMTP.class, e);
88 Target.root.accept(m);
92 public static class SMTPException extends MailException {
95 public SMTPException(String s) {
97 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
98 message = s.substring(s.indexOf(' ')+1);
99 } catch (NumberFormatException nfe) {
104 public String toString() { return "SMTP " + code + ": " + message; }
105 public String getMessage() { return toString(); }
108 // Server //////////////////////////////////////////////////////////////////////////////
110 public static class Server {
111 public void handleRequest(Connection conn) throws IOException {
112 conn.setTimeout(5 * 60 * 1000);
113 conn.setNewline("\r\n");
114 conn.println("220 " + conn.vhost + " ESMTP " + this.getClass().getName());
116 Vector to = new Vector();
117 boolean ehlo = false;
118 String remotehost = null;
119 String authenticatedAs = null;
120 int failedRcptCount = 0;
121 for(String command = conn.readln(); ; command = conn.readln()) try {
122 if (command == null) return;
123 Log.warn("**"+conn.getRemoteAddress()+"**", command);
124 String c = command.toUpperCase();
125 if (c.startsWith("HELO")) {
126 remotehost = c.substring(5).trim();
127 conn.println("250 HELO " + conn.vhost);
128 from = null; to = new Vector();
129 } else if (c.startsWith("EHLO")) {
130 remotehost = c.substring(5).trim();
131 conn.println("250-"+conn.vhost);
132 //conn.println("250-AUTH");
133 conn.println("250-AUTH PLAIN");
134 //conn.println("250-STARTTLS");
135 conn.println("250 HELP");
137 from = null; to = new Vector();
138 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
139 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
140 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
141 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
142 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
143 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
144 } else if (c.startsWith("STARTTLS")) {
145 conn.println("220 starting TLS...");
147 conn = conn.negotiateSSL(true);
148 from = null; to = new Vector();
149 } else if (c.startsWith("AUTH")) {
150 if (authenticatedAs != null) {
151 conn.println("503 you are already authenticated; you must reconnect to reauth");
153 String mechanism = command.substring(4).trim();
155 if (mechanism.indexOf(' ')!=-1) {
156 rest = mechanism.substring(mechanism.indexOf(' ')+1).trim();
157 mechanism = mechanism.substring(0, mechanism.indexOf(' '));
159 if (mechanism.equals("PLAIN")) {
160 // 538 Encryption required for requested authentication mechanism?
161 byte[] bytes = Encode.fromBase64(rest);
162 String authenticateUser = null;
163 String authorizeUser = null;
164 String password = null;
166 for(int i=0; i<=bytes.length; i++) {
167 if (i<bytes.length && bytes[i]!=0) continue;
168 String result = new String(bytes, start, i-start, "UTF-8");
169 if (authenticateUser==null) authenticateUser = result;
170 else if (authorizeUser==null) authorizeUser = result;
171 else if (password==null) password = result;
174 // FIXME: be smarter here
175 if (Main.auth.login(authorizeUser, password)!=null)
176 authenticatedAs = authenticateUser;
177 conn.println("235 Authentication successful");
179 } else if (mechanism.equals("CRAM-MD5")) {
181 conn.println("334 "+challenge);
182 String resp = conn.readln();
183 if (resp.equals("*")) {
184 conn.println("501 client requested AUTH cancellation");
186 } else if (mechanism.equals("ANONYMOUS")) {
187 } else if (mechanism.equals("EXTERNAL")) {
188 } else if (mechanism.equals("DIGEST-MD5")) {
191 conn.println("504 unrecognized authentication type");
193 // on success, reset to initial state; client will EHLO again
194 from = null; to = new Vector();
196 } else if (c.startsWith("MAIL FROM:")) {
197 command = command.substring(10).trim();
198 from = command.equals("<>") ? null : new Address(command);
199 conn.println("250 " + from + " is syntactically correct");
200 // FEATURE: perform SMTP validation on the address, reject if invalid
201 } else if (c.startsWith("RCPT TO:")) {
202 // some clients are broken and put RCPT first; we will tolerate this
203 command = command.substring(8).trim();
204 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
205 Address addr = new Address(command);
206 if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
207 conn.println("250 you are connected locally, so I will let you send");
209 if (!whitelist.isWhitelisted(addr))
210 whitelist.addWhitelist(addr);
211 } else if (authenticatedAs!=null) {
212 conn.println("250 you are authenticated as "+authenticatedAs+", so I will let you send");
214 if (!whitelist.isWhitelisted(addr))
215 whitelist.addWhitelist(addr);
216 } else if (addr.isLocal()) {
218 conn.println("536 sorry, limit on 3 RCPT TO's per DATA");
220 // FEATURE: should check the address further and give 550 if undeliverable
221 conn.println("250 " + addr + " is on this machine; I will deliver it");
225 conn.println("535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
226 Log.warn("","535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
228 if (failedRcptCount > 3) {
234 } else if (c.startsWith("DATA")) {
235 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
236 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
237 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress() && authenticatedAs==null) {
238 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
239 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
240 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
241 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
242 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
245 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
246 graylist.addWhitelist(conn.getRemoteAddress());
247 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
248 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
250 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
252 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
256 conn.println("354 Enter message, ending with \".\" on a line by itself");
260 // FIXME: deal with messages larger than memory here?
261 StringBuffer buf = new StringBuffer();
262 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
263 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
265 // FIXME: this is leaking BCC addrs
266 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
267 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
269 // FIXME: some sort of stream transformer here?
271 String s = conn.readln();
272 if (s == null) throw new RuntimeException("connection closed");
273 if (s.equals(".")) break;
274 if (s.startsWith(".")) s = s.substring(1);
275 buf.append(s + "\r\n");
276 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE && (from+"").indexOf("paperless")==-1) {
277 Log.error("**"+conn.getRemoteAddress()+"**",
278 "sorry, this mail server only accepts messages of less than " +
279 ByteSize.toString(MAX_MESSAGE_SIZE));
280 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
281 ByteSize.toString(MAX_MESSAGE_SIZE));
284 String message = buf.toString();
286 for(int i=0; i<to.size(); i++)
287 enqueue(m = Message.newMessage(Fountain.Util.create(message)).withEnvelope(from, (Address)to.elementAt(i)));
288 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
289 conn.println("250 message accepted");
291 from = null; to = new Vector();
292 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
293 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
294 } catch (Script.Later.LaterException le) { conn.println("453 try again later");
295 } catch (Script.Reject.RejectException re) {
296 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
297 conn.println("501 " + re.reason);
299 } else { conn.println("500 unrecognized command"); }
300 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
305 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
307 public static class Outgoing extends Thread {
309 private static final HashMap deadHosts = new HashMap();
310 public static void enqueue(Message m) throws IOException {
311 if (m == null) { Log.warn(Outgoing.class, "attempted to enqueue(null)"); return; }
312 String traces = m.headers.get("Received");
315 for(int i=0; i<traces.length(); i++)
316 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
318 if (lines > 100) { // required by rfc
319 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
323 synchronized(Outgoing.class) {
324 spool.insert(m, Mailbox.Flag.defaultFlags);
325 Outgoing.class.notifyAll();
329 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
330 public static boolean attempt(Message m, boolean noBounces) throws IOException {
331 if (m.envelopeTo == null) {
332 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
335 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
336 if (mx.length == 0) {
338 enqueue(m.bounce("could not resolve " + m.envelopeTo.host));
341 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
345 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
347 enqueue(m.bounce("could not send for 5 days"));
350 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
354 for(int i=0; i<mx.length; i++) {
355 //if (deadHosts.contains(mx[i])) continue;
356 if (attempt(m, mx[i])) return true;
361 private static void check(String s, Connection conn) {
363 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
364 //if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
365 if (!s.startsWith("2")&&!s.startsWith("3")) throw new SMTPException(s);
367 private static boolean attempt(final Message m, final InetAddress mx) {
368 boolean accepted = false;
369 Connection conn = null;
371 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
372 conn.setNewline("\r\n");
373 conn.setTimeout(60 * 1000);
374 check(conn.readln(), conn); // banner
376 conn.println("EHLO " + conn.vhost);
377 check(conn.readln(), conn);
378 } catch (SMTPException smtpe) {
379 conn.println("HELO " + conn.vhost);
380 check(conn.readln(), conn);
382 String envelopeFrom = m.envelopeFrom==null ? "" : m.envelopeFrom.toString();
383 conn.println("MAIL FROM:<" + envelopeFrom +">"); check(conn.readln(), conn);
384 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
385 conn.println("DATA"); check(conn.readln(), conn);
387 Headers head = new Headers(m.headers,
392 Stream stream = head.getStream();
393 for(String s = stream.readln(); s!=null; s=stream.readln()) {
394 if (s.startsWith(".")) conn.print(".");
398 stream = m.getBody().getStream();
399 for(String s = stream.readln(); s!=null; s=stream.readln()) {
400 if (s.startsWith(".")) conn.print(".");
404 String resp = conn.readln();
406 throw new SMTPException("server " + mx + " closed connection without accepting message");
408 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
411 } catch (SMTPException e) {
412 if (accepted) return true;
413 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
414 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
415 Log.warn(SMTP.Outgoing.class, e);
417 // FIXME: we should not be bouncing here!
418 if (e.code >= 500 && e.code <= 599) {
420 attempt(m.bounce("unable to deliver: " + e), true);
421 } catch (Exception ex) {
422 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
423 Log.error(SMTP.Outgoing.class, ex);
429 } catch (Exception e) {
430 if (accepted) return true;
431 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
432 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
433 Log.warn(SMTP.Outgoing.class, e);
434 //if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
437 if (conn != null) conn.close();
442 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
443 private static int serials = 1;
444 private int serial = serials++;
445 private Mailbox.Iterator it;
448 synchronized(Outgoing.class) {
454 int count = spool.count(Query.all());
455 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
458 boolean good = false;
459 synchronized(Outgoing.class) {
460 it = spool.iterator();
461 OUTER: for(; it.next(); ) {
462 for(Outgoing o : threads)
463 if (o!=this && o.it != null && o.it.uid()==it.uid())
471 if (attempt(it.cur())) it.delete();
472 } catch (Exception e) {
473 Log.error(SMTP.Outgoing.class, e);
475 Log.info(this, "sleeping for 3s...");
478 } catch (Exception e) {
479 //if (e instanceof InterruptedException) throw e;
480 Log.error(SMTP.Outgoing.class, e);
482 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
489 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
492 synchronized(Outgoing.class) {
493 Outgoing.class.wait(5 * 60 * 1000);
496 } catch (InterruptedException e) { Log.warn(this, e); }
500 public static InetAddress[] getMailExchangerIPs(String hostName) {
503 Hashtable env = new Hashtable();
504 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
505 DirContext ictx = new InitialDirContext(env);
506 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
507 Attribute attr = attrs.get("MX");
509 ret = new InetAddress[1];
511 ret[0] = InetAddress.getByName(hostName);
512 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
514 } catch (UnknownHostException uhe) {
515 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
516 return new InetAddress[0];
519 ret = new InetAddress[attr.size()];
520 NamingEnumeration ne = attr.getAll();
521 for(int i=0; ne.hasMore();) {
522 String mx = (String)ne.next();
523 // FIXME we should be sorting here
524 mx = mx.substring(mx.indexOf(" ") + 1);
525 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
526 InetAddress ia = InetAddress.getByName(mx);
527 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
531 } catch (Exception e) {
532 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
533 Log.warn(SMTP.class, e);
534 return new InetAddress[0];