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
20 // RFC2554: SMTP Service Extension for Authentication
21 // - did not implement section 5, though
22 // RFC4616: SASL PLAIN
24 // Note: we can't actually use status codes for feedback if we accept
25 // multiple destination addresses... a failure on one and success on
28 // FIXME: logging: current logging sucks
29 // FIXME: loop prevention
30 // FIXME: probably need some throttling on outbound mail
32 // FEATURE: public static boolean validate(Address a)
33 // FEATURE: rate-limiting
35 // FEATURE: infer messageid, date, if not present (?)
36 // FEATURE: exponential backoff on retry time?
37 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
38 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
39 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
40 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
43 public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
44 public static final int numOutgoingThreads = 5;
46 public static final int GRAYLIST_MINWAIT = 1000 * 60 * 60; // one hour
47 public static final int GRAYLIST_MAXWAIT = 1000 * 60 * 60 * 24 * 5; // five days
49 public static final Graylist graylist =
50 new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite");
52 public static final Whitelist whitelist =
53 new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite");
55 public static final int MAX_MESSAGE_SIZE =
56 Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
58 private static final Mailbox spool =
59 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true).getMailbox();
62 for(int i=0; i<numOutgoingThreads; i++)
63 new Outgoing().start();
66 public static void enqueue(Message m) throws IOException {
67 if (!m.envelopeTo.isLocal()) Outgoing.enqueue(m);
68 else Target.root.accept(m);
71 public static class SMTPException extends MailException {
74 public SMTPException(String s) {
76 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
77 message = s.substring(s.indexOf(' ')+1);
78 } catch (NumberFormatException nfe) {
83 public String toString() { return "SMTP " + code + ": " + message; }
84 public String getMessage() { return toString(); }
87 // Server //////////////////////////////////////////////////////////////////////////////
89 public static class Server {
90 public void handleRequest(Connection conn) throws IOException {
91 conn.setTimeout(5 * 60 * 1000);
92 conn.setNewline("\r\n");
93 conn.println("220 " + conn.vhost + " ESMTP " + this.getClass().getName());
95 Vector to = new Vector();
97 String remotehost = null;
98 String authenticatedAs = null;
99 int failedRcptCount = 0;
100 for(String command = conn.readln(); ; command = conn.readln()) try {
101 if (command == null) return;
102 Log.warn("**"+conn.getRemoteAddress()+"**", command);
103 String c = command.toUpperCase();
104 if (c.startsWith("HELO")) {
105 remotehost = c.substring(5).trim();
106 conn.println("250 HELO " + conn.vhost);
107 from = null; to = new Vector();
108 } else if (c.startsWith("EHLO")) {
109 remotehost = c.substring(5).trim();
110 conn.println("250-"+conn.vhost);
111 //conn.println("250-AUTH");
112 conn.println("250-AUTH PLAIN");
113 //conn.println("250-STARTTLS");
114 conn.println("250 HELP");
116 from = null; to = new Vector();
117 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
118 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
119 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
120 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
121 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
122 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
123 } else if (c.startsWith("STARTTLS")) {
124 conn.println("220 starting TLS...");
126 conn = conn.negotiateSSL(true);
127 from = null; to = new Vector();
128 } else if (c.startsWith("AUTH")) {
129 if (authenticatedAs != null) {
130 conn.println("503 you are already authenticated; you must reconnect to reauth");
132 String mechanism = command.substring(4).trim();
134 if (mechanism.indexOf(' ')!=-1) {
135 rest = mechanism.substring(mechanism.indexOf(' ')+1).trim();
136 mechanism = mechanism.substring(0, mechanism.indexOf(' '));
138 if (mechanism.equals("PLAIN")) {
139 // 538 Encryption required for requested authentication mechanism?
140 byte[] bytes = Encode.fromBase64(rest);
141 String authenticateUser = null;
142 String authorizeUser = null;
143 String password = null;
145 for(int i=0; i<=bytes.length; i++) {
146 if (i<bytes.length && bytes[i]!=0) continue;
147 String result = new String(bytes, start, i-start, "UTF-8");
148 if (authenticateUser==null) authenticateUser = result;
149 else if (authorizeUser==null) authorizeUser = result;
150 else if (password==null) password = result;
153 // FIXME: be smarter here
154 if (Main.auth.login(authorizeUser, password)!=null)
155 authenticatedAs = authenticateUser;
156 conn.println("235 Authentication successful");
158 } else if (mechanism.equals("CRAM-MD5")) {
160 conn.println("334 "+challenge);
161 String resp = conn.readln();
162 if (resp.equals("*")) {
163 conn.println("501 client requested AUTH cancellation");
165 } else if (mechanism.equals("ANONYMOUS")) {
166 } else if (mechanism.equals("EXTERNAL")) {
167 } else if (mechanism.equals("DIGEST-MD5")) {
170 conn.println("504 unrecognized authentication type");
172 // on success, reset to initial state; client will EHLO again
173 from = null; to = new Vector();
175 } else if (c.startsWith("MAIL FROM:")) {
176 command = command.substring(10).trim();
177 from = command.equals("<>") ? null : new Address(command);
178 conn.println("250 " + from + " is syntactically correct");
179 // FEATURE: perform SMTP validation on the address, reject if invalid
180 } else if (c.startsWith("RCPT TO:")) {
181 // some clients are broken and put RCPT first; we will tolerate this
182 command = command.substring(8).trim();
183 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
184 Address addr = new Address(command);
185 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 if (!whitelist.isWhitelisted(addr))
189 whitelist.addWhitelist(addr);
190 } else if (authenticatedAs!=null) {
191 conn.println("250 you are authenticated as "+authenticatedAs+", so I will let you send");
193 if (!whitelist.isWhitelisted(addr))
194 whitelist.addWhitelist(addr);
195 } else if (addr.isLocal()) {
197 conn.println("536 sorry, limit on 3 RCPT TO's per DATA");
199 // FEATURE: should check the address further and give 550 if undeliverable
200 conn.println("250 " + addr + " is on this machine; I will deliver it");
204 conn.println("535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
205 Log.warn("","535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
207 if (failedRcptCount > 3) {
213 } else if (c.startsWith("DATA")) {
214 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
215 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
216 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress() && authenticatedAs==null) {
217 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
218 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
219 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
220 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
221 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
224 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
225 graylist.addWhitelist(conn.getRemoteAddress());
226 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
227 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
229 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
231 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
235 conn.println("354 Enter message, ending with \".\" on a line by itself");
239 // FIXME: deal with messages larger than memory here?
240 StringBuffer buf = new StringBuffer();
241 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
242 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
244 // FIXME: this is leaking BCC addrs
245 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
246 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
248 // FIXME: some sort of stream transformer here?
250 String s = conn.readln();
251 if (s == null) throw new RuntimeException("connection closed");
252 if (s.equals(".")) break;
253 if (s.startsWith(".")) s = s.substring(1);
254 buf.append(s + "\r\n");
255 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE && (from+"").indexOf("paperless")==-1) {
256 Log.error("**"+conn.getRemoteAddress()+"**",
257 "sorry, this mail server only accepts messages of less than " +
258 ByteSize.toString(MAX_MESSAGE_SIZE));
259 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
260 ByteSize.toString(MAX_MESSAGE_SIZE));
263 String message = buf.toString();
265 for(int i=0; i<to.size(); i++)
266 enqueue(m = Message.newMessage(Fountain.Util.create(message)).withEnvelope(from, (Address)to.elementAt(i)));
267 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
268 conn.println("250 message accepted");
270 from = null; to = new Vector();
271 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
272 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
273 } catch (Script.Later.LaterException le) { conn.println("453 try again later");
274 } catch (Script.Reject.RejectException re) {
275 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
276 conn.println("501 " + re.reason);
278 } else { conn.println("500 unrecognized command"); }
279 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
284 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
286 public static class Outgoing extends Thread {
288 private static final HashMap deadHosts = new HashMap();
289 public static void enqueue(Message m) throws IOException {
290 if (m == null) { Log.warn(Outgoing.class, "attempted to enqueue(null)"); return; }
291 String traces = m.headers.get("Received");
294 for(int i=0; i<traces.length(); i++)
295 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
297 if (lines > 100) { // required by rfc
298 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
302 synchronized(Outgoing.class) {
303 spool.insert(m, Mailbox.Flag.defaultFlags);
304 Outgoing.class.notifyAll();
308 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
309 public static boolean attempt(Message m, boolean noBounces) throws IOException {
310 if (m.envelopeTo == null) {
311 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
314 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
315 if (mx.length == 0) {
317 enqueue(m.bounce("could not resolve " + m.envelopeTo.host));
320 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
324 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
326 enqueue(m.bounce("could not send for 5 days"));
329 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
333 for(int i=0; i<mx.length; i++) {
334 //if (deadHosts.contains(mx[i])) continue;
335 if (attempt(m, mx[i])) return true;
340 private static void check(String s, Connection conn) {
342 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
343 //if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
344 if (!s.startsWith("2")&&!s.startsWith("3")) throw new SMTPException(s);
346 private static boolean attempt(final Message m, final InetAddress mx) {
347 boolean accepted = false;
348 Connection conn = null;
350 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
351 conn.setNewline("\r\n");
352 conn.setTimeout(60 * 1000);
353 check(conn.readln(), conn); // banner
355 conn.println("EHLO " + conn.vhost);
356 check(conn.readln(), conn);
357 } catch (SMTPException smtpe) {
358 conn.println("HELO " + conn.vhost);
359 check(conn.readln(), conn);
361 String envelopeFrom = m.envelopeFrom==null ? "" : m.envelopeFrom.toString();
362 conn.println("MAIL FROM:<" + envelopeFrom +">"); check(conn.readln(), conn);
363 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
364 conn.println("DATA"); check(conn.readln(), conn);
366 Headers head = new Headers(m.headers,
371 Stream stream = head.getStream();
372 for(String s = stream.readln(); s!=null; s=stream.readln()) {
373 if (s.startsWith(".")) conn.print(".");
377 stream = m.getBody().getStream();
378 for(String s = stream.readln(); s!=null; s=stream.readln()) {
379 if (s.startsWith(".")) conn.print(".");
383 String resp = conn.readln();
385 throw new SMTPException("server " + mx + " closed connection without accepting message");
387 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
390 } catch (SMTPException e) {
391 if (accepted) return true;
392 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
393 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
394 Log.warn(SMTP.Outgoing.class, e);
396 // FIXME: we should not be bouncing here!
397 if (e.code >= 500 && e.code <= 599) {
399 attempt(m.bounce("unable to deliver: " + e), true);
400 } catch (Exception ex) {
401 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
402 Log.error(SMTP.Outgoing.class, ex);
408 } catch (Exception e) {
409 if (accepted) return true;
410 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
411 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
412 Log.warn(SMTP.Outgoing.class, e);
413 //if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
416 if (conn != null) conn.close();
421 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
422 private static int serials = 1;
423 private int serial = serials++;
424 private Mailbox.Iterator it;
427 synchronized(Outgoing.class) {
433 int count = spool.count(Query.all());
434 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
437 boolean good = false;
438 synchronized(Outgoing.class) {
439 it = spool.iterator();
440 OUTER: for(; it.next(); ) {
441 for(Outgoing o : threads)
442 if (o!=this && o.it != null && o.it.uid()==it.uid())
450 if (attempt(it.cur())) it.delete();
451 } catch (Exception e) {
452 Log.error(SMTP.Outgoing.class, e);
454 Log.info(this, "sleeping for 3s...");
457 } catch (Exception e) {
458 //if (e instanceof InterruptedException) throw e;
459 Log.error(SMTP.Outgoing.class, e);
461 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
468 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
471 synchronized(Outgoing.class) {
472 Outgoing.class.wait(5 * 60 * 1000);
475 } catch (InterruptedException e) { Log.warn(this, e); }
479 public static InetAddress[] getMailExchangerIPs(String hostName) {
482 Hashtable env = new Hashtable();
483 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
484 DirContext ictx = new InitialDirContext(env);
485 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
486 Attribute attr = attrs.get("MX");
488 ret = new InetAddress[1];
490 ret[0] = InetAddress.getByName(hostName);
491 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
493 } catch (UnknownHostException uhe) {
494 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
495 return new InetAddress[0];
498 ret = new InetAddress[attr.size()];
499 NamingEnumeration ne = attr.getAll();
500 for(int i=0; ne.hasMore();) {
501 String mx = (String)ne.next();
502 // FIXME we should be sorting here
503 mx = mx.substring(mx.indexOf(" ") + 1);
504 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
505 InetAddress ia = InetAddress.getByName(mx);
506 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
510 } catch (Exception e) {
511 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
512 Log.warn(SMTP.class, e);
513 return new InetAddress[0];