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.*;
15 // FIXME: inbound throttling/ratelimiting
17 // "Address enumeration detection" -- notice when it looks like somebody
18 // is trying a raft of addresses.
21 // RFC2554: SMTP Service Extension for Authentication
22 // - did not implement section 5, though
23 // RFC4616: SASL PLAIN
25 // Note: we can't actually use status codes for feedback if we accept
26 // multiple destination addresses... a failure on one and success on
29 // FIXME: logging: current logging sucks
30 // FIXME: loop prevention
31 // FIXME: probably need some throttling on outbound mail
33 // FEATURE: public static boolean validate(Address a)
34 // FEATURE: rate-limiting
36 // FEATURE: infer messageid, date, if not present (?)
37 // FEATURE: exponential backoff on retry time?
38 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
39 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
40 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
41 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
44 public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
45 public static final int numOutgoingThreads = 5;
47 private static final SqliteMailbox allmail =
48 (SqliteMailbox)FileBasedMailbox
49 .getFileBasedMailbox("/afs/megacz.com/mail/user/megacz/allmail", false);
51 public static final int GRAYLIST_MINWAIT = 1000 * 60 * 60; // one hour
52 public static final int GRAYLIST_MAXWAIT = 1000 * 60 * 60 * 24 * 5; // five days
54 public static final int RETRY_TIME = 1000 * 60 * 30;
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 // Don't perform SAV; discouraged here
201 // http://blog.fastmail.fm/2007/12/05/sending-email-servers-best-practice/
202 } else if (c.startsWith("RCPT TO:")) {
203 // some clients are broken and put RCPT first; we will tolerate this
204 command = command.substring(8).trim();
205 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
206 Address addr = new Address(command);
207 if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
208 conn.println("250 you are connected locally, so I will let you send");
210 if (!whitelist.isWhitelisted(addr))
211 whitelist.addWhitelist(addr);
212 } else if (authenticatedAs!=null) {
213 conn.println("250 you are authenticated as "+authenticatedAs+", so I will let you send");
215 if (!whitelist.isWhitelisted(addr))
216 whitelist.addWhitelist(addr);
217 } else if (addr.isLocal()) {
219 conn.println("536 sorry, limit on 3 RCPT TO's per DATA");
221 // FEATURE: should check the address further and give 550 if undeliverable
222 conn.println("250 " + addr + " is on this machine; I will deliver it");
226 conn.println("535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
227 Log.warn("","535 sorry, " + addr + " is not on this machine, you are not connected from localhost, and I will not relay without SMTP AUTH");
229 if (failedRcptCount > 3) {
235 } else if (c.startsWith("DATA")) {
236 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
237 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
238 if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress() && authenticatedAs==null) {
239 long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"");
240 if (when == 0 || System.currentTimeMillis() - when > GRAYLIST_MAXWAIT) {
241 graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis());
242 conn.println("451 you are graylisted; please try back in one hour to be whitelisted");
243 Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted");
246 } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) {
247 graylist.addWhitelist(conn.getRemoteAddress());
248 conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself");
249 Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted");
251 conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")");
253 Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")");
257 conn.println("354 Enter message, ending with \".\" on a line by itself");
261 // FIXME: deal with messages larger than memory here?
262 StringBuffer buf = new StringBuffer();
263 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
264 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
266 // FIXME: this is leaking BCC addrs
267 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
268 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
270 // FIXME: some sort of stream transformer here?
272 String s = conn.readln();
273 if (s == null) throw new RuntimeException("connection closed");
274 if (s.equals(".")) break;
275 if (s.startsWith(".")) s = s.substring(1);
276 buf.append(s + "\r\n");
277 if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE && (from+"").indexOf("paperless")==-1) {
278 Log.error("**"+conn.getRemoteAddress()+"**",
279 "sorry, this mail server only accepts messages of less than " +
280 ByteSize.toString(MAX_MESSAGE_SIZE));
281 throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " +
282 ByteSize.toString(MAX_MESSAGE_SIZE));
285 String message = buf.toString();
287 for(int i=0; i<to.size(); i++)
288 enqueue(m = Message.newMessage(Fountain.Util.create(message)).withEnvelope(from, (Address)to.elementAt(i)));
289 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
290 conn.println("250 message accepted");
292 from = null; to = new Vector();
293 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
294 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
295 } catch (Script.Later.LaterException le) { conn.println("453 try again later");
296 } catch (Script.Reject.RejectException re) {
297 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
298 conn.println("501 " + re.reason);
300 } else { conn.println("500 unrecognized command"); }
301 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
306 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
308 public static class Outgoing extends Thread {
310 private static final HashMap deadHosts = new HashMap();
311 public static void enqueue(Message m) throws IOException {
312 if (m == null) { Log.warn(Outgoing.class, "attempted to enqueue(null)"); return; }
313 String traces = m.headers.get("Received");
316 for(int i=0; i<traces.length(); i++)
317 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
319 if (lines > 100) { // required by rfc
320 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
324 synchronized(Outgoing.class) {
325 spool.insert(m, Mailbox.Flag.defaultFlags);
326 Outgoing.class.notifyAll();
330 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
331 public static boolean attempt(Message m, boolean noBounces) throws IOException {
332 if (m.envelopeTo == null) {
333 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
336 InetAddress[] mx = DNSUtil.getMailExchangerIPs(m.envelopeTo.host);
337 if (mx.length == 0) {
339 enqueue(m.bounce("could not resolve " + m.envelopeTo.host));
342 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
346 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
348 enqueue(m.bounce("could not send for 5 days"));
351 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
355 for(int i=0; i<mx.length; i++) {
356 //if (deadHosts.contains(mx[i])) continue;
357 if (attempt(m, mx[i])) return true;
362 private static void check(String s, Connection conn) {
364 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
365 //if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
366 if (!s.startsWith("2")&&!s.startsWith("3")) throw new SMTPException(s);
368 private static boolean attempt(final Message m, final InetAddress mx) {
369 boolean accepted = false;
370 Connection conn = null;
372 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
373 InetAddress localAddress = conn.getSocket().getLocalAddress();
374 String reverse = DNSUtil.reverseLookup(localAddress);
375 Log.info(SMTP.Outgoing.class,
376 "outbound connection to " + mx + " uses " + localAddress + " [reverse: " + reverse + "]");
377 InetAddress relookup = InetAddress.getByName(reverse);
378 if (!relookup.equals(localAddress))
379 Log.error(SMTP.Outgoing.class,
380 "Warning: local machine fails forward-confirmed-reverse; " +
381 reverse + " resolves to " + localAddress);
382 conn.setNewline("\r\n");
383 conn.setTimeout(60 * 1000);
384 check(conn.readln(), conn); // banner
386 conn.println("EHLO " + reverse);
387 check(conn.readln(), conn);
388 } catch (SMTPException smtpe) {
389 conn.println("HELO " + reverse);
390 check(conn.readln(), conn);
392 String envelopeFrom = m.envelopeFrom==null ? "" : m.envelopeFrom.toString();
393 conn.println("MAIL FROM:<" + envelopeFrom +">"); check(conn.readln(), conn);
394 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
395 conn.println("DATA"); check(conn.readln(), conn);
397 Headers head = new Headers(m.headers,
402 Stream stream = head.getStream();
403 for(String s = stream.readln(); s!=null; s=stream.readln()) {
404 if (s.startsWith(".")) conn.print(".");
408 stream = m.getBody().getStream();
409 for(String s = stream.readln(); s!=null; s=stream.readln()) {
410 if (s.startsWith(".")) conn.print(".");
414 String resp = conn.readln();
416 throw new SMTPException("server " + mx + " closed connection without accepting message");
418 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
421 } catch (SMTPException e) {
422 if (accepted) return true;
423 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
424 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
425 Log.warn(SMTP.Outgoing.class, e);
427 // FIXME: we should not be bouncing here!
428 if (e.code >= 500 && e.code <= 599) {
430 attempt(m.bounce("unable to deliver: " + e), true);
431 } catch (Exception ex) {
432 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
433 Log.error(SMTP.Outgoing.class, ex);
439 } catch (Exception e) {
440 if (accepted) return true;
441 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
442 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
443 Log.warn(SMTP.Outgoing.class, e);
444 //if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
447 if (conn != null) conn.close();
452 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
453 private static int serials = 1;
454 private int serial = serials++;
455 private Mailbox.Iterator it;
457 private static Map<String,Long> nextTry = Collections.synchronizedMap(new HashMap<String,Long>());
460 synchronized(Outgoing.class) {
466 int count = spool.count(Query.all());
467 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
470 boolean good = false;
471 synchronized(Outgoing.class) {
472 it = spool.iterator();
473 OUTER: for(; it.next(); ) {
474 for(Outgoing o : threads)
475 if (o!=this && o.it != null && o.it.uid()==it.uid())
483 String messageid = it.cur().messageid;
484 if (nextTry.get(messageid) == null || System.currentTimeMillis() > nextTry.get(messageid)) {
485 boolean ok = attempt(it.cur());
487 else nextTry.put(messageid, System.currentTimeMillis() + RETRY_TIME);
489 } catch (Exception e) {
490 Log.error(SMTP.Outgoing.class, e);
492 Log.info(this, "sleeping for 3s...");
495 } catch (Exception e) {
496 //if (e instanceof InterruptedException) throw e;
497 Log.error(SMTP.Outgoing.class, e);
499 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
506 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
509 synchronized(Outgoing.class) {
510 Outgoing.class.wait(5 * 60 * 1000);
513 } catch (InterruptedException e) { Log.warn(this, e); }