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 public static final Whitelist whitelist;
53 graylist = new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite");
54 whitelist = new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite");
55 } catch (Exception e) {
56 throw new RuntimeException(e);
60 public static final int MAX_MESSAGE_SIZE =
61 Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1"));
63 private static final Mailbox spool =
64 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true).getMailbox();
67 for(int i=0; i<numOutgoingThreads; i++)
68 new Outgoing().start();
71 public static void enqueue(Message m) throws IOException {
72 if (!m.envelopeTo.isLocal()) Outgoing.enqueue(m);
73 else Target.root.accept(m);
76 public static class SMTPException extends MailException {
79 public SMTPException(String s) {
81 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
82 message = s.substring(s.indexOf(' ')+1);
83 } catch (NumberFormatException nfe) {
88 public String toString() { return "SMTP " + code + ": " + message; }
89 public String getMessage() { return toString(); }
92 // Server //////////////////////////////////////////////////////////////////////////////
94 public static class Server {
95 public void handleRequest(Connection conn) throws IOException {
96 conn.setTimeout(5 * 60 * 1000);
97 conn.setNewline("\r\n");
98 conn.println("220 " + conn.vhost + " ESMTP " + this.getClass().getName());
100 Vector to = new Vector();
101 boolean ehlo = false;
102 String remotehost = null;
103 String authenticatedAs = null;
104 int failedRcptCount = 0;
105 for(String command = conn.readln(); ; command = conn.readln()) try {
106 if (command == null) return;
107 Log.warn("**"+conn.getRemoteAddress()+"**", command);
108 String c = command.toUpperCase();
109 if (c.startsWith("HELO")) {
110 remotehost = c.substring(5).trim();
111 conn.println("250 HELO " + conn.vhost);
112 from = null; to = new Vector();
113 } else if (c.startsWith("EHLO")) {
114 remotehost = c.substring(5).trim();
115 conn.println("250-"+conn.vhost);
116 //conn.println("250-AUTH");
117 conn.println("250-AUTH PLAIN");
118 //conn.println("250-STARTTLS");
119 conn.println("250 HELP");
121 from = null; to = new Vector();
122 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
123 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
124 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
125 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
126 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
127 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
128 } else if (c.startsWith("STARTTLS")) {
129 conn.println("220 starting TLS...");
131 conn = conn.negotiateSSL(true);
132 from = null; to = new Vector();
133 } else if (c.startsWith("AUTH")) {
134 if (authenticatedAs != null) {
135 conn.println("503 you are already authenticated; you must reconnect to reauth");
137 String mechanism = command.substring(4).trim();
139 if (mechanism.indexOf(' ')!=-1) {
140 rest = mechanism.substring(mechanism.indexOf(' ')+1).trim();
141 mechanism = mechanism.substring(0, mechanism.indexOf(' '));
143 if (mechanism.equals("PLAIN")) {
144 // 538 Encryption required for requested authentication mechanism?
145 byte[] bytes = Encode.fromBase64(rest);
146 String authenticateUser = null;
147 String authorizeUser = null;
148 String password = null;
150 for(int i=0; i<=bytes.length; i++) {
151 if (i<bytes.length && bytes[i]!=0) continue;
152 String result = new String(bytes, start, i-start, "UTF-8");
153 if (authenticateUser==null) authenticateUser = result;
154 else if (authorizeUser==null) authorizeUser = result;
155 else if (password==null) password = result;
158 // FIXME: be smarter here
159 if (Main.auth.login(authorizeUser, password)!=null)
160 authenticatedAs = authenticateUser;
161 conn.println("235 Authentication successful");
163 } else if (mechanism.equals("CRAM-MD5")) {
165 conn.println("334 "+challenge);
166 String resp = conn.readln();
167 if (resp.equals("*")) {
168 conn.println("501 client requested AUTH cancellation");
170 } else if (mechanism.equals("ANONYMOUS")) {
171 } else if (mechanism.equals("EXTERNAL")) {
172 } else if (mechanism.equals("DIGEST-MD5")) {
175 conn.println("504 unrecognized authentication type");
177 // on success, reset to initial state; client will EHLO again
178 from = null; to = new Vector();
180 } else if (c.startsWith("MAIL FROM:")) {
181 command = command.substring(10).trim();
182 from = command.equals("<>") ? null : new Address(command);
183 conn.println("250 " + from + " is syntactically correct");
184 // FEATURE: perform SMTP validation on the address, reject if invalid
185 } else if (c.startsWith("RCPT TO:")) {
186 // some clients are broken and put RCPT first; we will tolerate this
187 command = command.substring(8).trim();
188 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
189 Address addr = new Address(command);
190 if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
191 conn.println("250 you are connected locally, so I will let you send");
193 if (!whitelist.isWhitelisted(addr))
194 whitelist.addWhitelist(addr);
195 } else if (authenticatedAs!=null) {
196 conn.println("250 you are authenticated as "+authenticatedAs+", so I will let you send");
198 if (!whitelist.isWhitelisted(addr))
199 whitelist.addWhitelist(addr);
200 } else if (addr.isLocal()) {
202 conn.println("536 sorry, limit on 3 RCPT TO's per DATA");
204 // FEATURE: should check the address further and give 550 if undeliverable
205 conn.println("250 " + addr + " is on this machine; I will deliver it");
209 conn.println("535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
210 Log.warn("","535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
212 if (failedRcptCount > 3) {
218 } else if (c.startsWith("DATA")) {
219 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
220 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
221 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress() && authenticatedAs==null) {
222 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
223 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
224 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
225 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
226 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
229 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
230 graylist.addWhitelist(conn.getRemoteAddress());
231 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
232 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
234 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
236 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
240 conn.println("354 Enter message, ending with \".\" on a line by itself");
244 // FIXME: deal with messages larger than memory here?
245 StringBuffer buf = new StringBuffer();
246 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
247 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
249 // FIXME: this is leaking BCC addrs
250 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
251 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
253 // FIXME: some sort of stream transformer here?
255 String s = conn.readln();
256 if (s == null) throw new RuntimeException("connection closed");
257 if (s.equals(".")) break;
258 if (s.startsWith(".")) s = s.substring(1);
259 buf.append(s + "\r\n");
260 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE && (from+"").indexOf("paperless")==-1) {
261 Log.error("**"+conn.getRemoteAddress()+"**",
262 "sorry, this mail server only accepts messages of less than " +
263 ByteSize.toString(MAX_MESSAGE_SIZE));
264 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
265 ByteSize.toString(MAX_MESSAGE_SIZE));
268 String message = buf.toString();
270 for(int i=0; i<to.size(); i++)
271 enqueue(m = Message.newMessage(Fountain.Util.create(message)).withEnvelope(from, (Address)to.elementAt(i)));
272 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
273 conn.println("250 message accepted");
275 from = null; to = new Vector();
276 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
277 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
278 } catch (Script.Later.LaterException le) { conn.println("453 try again later");
279 } catch (Script.Reject.RejectException re) {
280 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
281 conn.println("501 " + re.reason);
283 } else { conn.println("500 unrecognized command"); }
284 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
289 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
291 public static class Outgoing extends Thread {
293 private static final HashMap deadHosts = new HashMap();
294 public static void enqueue(Message m) throws IOException {
295 if (m == null) { Log.warn(Outgoing.class, "attempted to enqueue(null)"); return; }
296 String traces = m.headers.get("Received");
299 for(int i=0; i<traces.length(); i++)
300 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
302 if (lines > 100) { // required by rfc
303 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
307 synchronized(Outgoing.class) {
308 spool.insert(m, Mailbox.Flag.defaultFlags);
309 Outgoing.class.notifyAll();
313 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
314 public static boolean attempt(Message m, boolean noBounces) throws IOException {
315 if (m.envelopeTo == null) {
316 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
319 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
320 if (mx.length == 0) {
322 enqueue(m.bounce("could not resolve " + m.envelopeTo.host));
325 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
329 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
331 enqueue(m.bounce("could not send for 5 days"));
334 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
338 for(int i=0; i<mx.length; i++) {
339 //if (deadHosts.contains(mx[i])) continue;
340 if (attempt(m, mx[i])) return true;
345 private static void check(String s, Connection conn) {
347 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
348 //if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
349 if (!s.startsWith("2")&&!s.startsWith("3")) throw new SMTPException(s);
351 private static boolean attempt(final Message m, final InetAddress mx) {
352 boolean accepted = false;
353 Connection conn = null;
355 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
356 conn.setNewline("\r\n");
357 conn.setTimeout(60 * 1000);
358 check(conn.readln(), conn); // banner
360 conn.println("EHLO " + conn.vhost);
361 check(conn.readln(), conn);
362 } catch (SMTPException smtpe) {
363 conn.println("HELO " + conn.vhost);
364 check(conn.readln(), conn);
366 String envelopeFrom = m.envelopeFrom==null ? "" : m.envelopeFrom.toString();
367 conn.println("MAIL FROM:<" + envelopeFrom +">"); check(conn.readln(), conn);
368 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
369 conn.println("DATA"); check(conn.readln(), conn);
371 Headers head = new Headers(m.headers,
376 Stream stream = head.getStream();
377 for(String s = stream.readln(); s!=null; s=stream.readln()) {
378 if (s.startsWith(".")) conn.print(".");
382 stream = m.getBody().getStream();
383 for(String s = stream.readln(); s!=null; s=stream.readln()) {
384 if (s.startsWith(".")) conn.print(".");
388 String resp = conn.readln();
390 throw new SMTPException("server " + mx + " closed connection without accepting message");
392 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
395 } catch (SMTPException e) {
396 if (accepted) return true;
397 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
398 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
399 Log.warn(SMTP.Outgoing.class, e);
401 // FIXME: we should not be bouncing here!
402 if (e.code >= 500 && e.code <= 599) {
404 attempt(m.bounce("unable to deliver: " + e), true);
405 } catch (Exception ex) {
406 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
407 Log.error(SMTP.Outgoing.class, ex);
413 } catch (Exception 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);
418 //if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
421 if (conn != null) conn.close();
426 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
427 private static int serials = 1;
428 private int serial = serials++;
429 private Mailbox.Iterator it;
432 synchronized(Outgoing.class) {
438 int count = spool.count(Query.all());
439 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
442 boolean good = false;
443 synchronized(Outgoing.class) {
444 it = spool.iterator();
445 OUTER: for(; it.next(); ) {
446 for(Outgoing o : threads)
447 if (o!=this && o.it != null && o.it.uid()==it.uid())
455 if (attempt(it.cur())) it.delete();
456 } catch (Exception e) {
457 Log.error(SMTP.Outgoing.class, e);
459 Log.info(this, "sleeping for 3s...");
462 } catch (Exception e) {
463 //if (e instanceof InterruptedException) throw e;
464 Log.error(SMTP.Outgoing.class, e);
466 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
473 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
476 synchronized(Outgoing.class) {
477 Outgoing.class.wait(5 * 60 * 1000);
480 } catch (InterruptedException e) { Log.warn(this, e); }
484 public static InetAddress[] getMailExchangerIPs(String hostName) {
487 Hashtable env = new Hashtable();
488 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
489 DirContext ictx = new InitialDirContext(env);
490 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
491 Attribute attr = attrs.get("MX");
493 ret = new InetAddress[1];
495 ret[0] = InetAddress.getByName(hostName);
496 if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
498 } catch (UnknownHostException uhe) {
499 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
500 return new InetAddress[0];
503 ret = new InetAddress[attr.size()];
504 NamingEnumeration ne = attr.getAll();
505 for(int i=0; ne.hasMore();) {
506 String mx = (String)ne.next();
507 // FIXME we should be sorting here
508 mx = mx.substring(mx.indexOf(" ") + 1);
509 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
510 InetAddress ia = InetAddress.getByName(mx);
511 if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
515 } catch (Exception e) {
516 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
517 Log.warn(SMTP.class, e);
518 return new InetAddress[0];