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.
5 package org.ibex.mail.protocol;
6 import org.ibex.mail.*;
7 import org.ibex.mail.target.*;
8 import org.ibex.util.*;
15 import javax.naming.*;
16 import javax.naming.directory.*;
18 // FIXME: logging: current logging sucks
19 // FIXME: loop prevention
23 // FEATURE: infer messageid, date, if not present (?)
24 // FEATURE: exponential backoff on retry time?
25 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
26 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
27 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
28 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
31 public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
32 public static final int numOutgoingThreads = 5;
33 private static final Mailbox spool =
34 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
37 for(int i=0; i<numOutgoingThreads; i++)
38 new Outgoing().start();
41 public static void accept(Message m) throws IOException {
42 if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
43 else Target.root.accept(m);
46 public static class SMTPException extends MailException {
49 public SMTPException(String s) {
51 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
52 message = s.substring(s.indexOf(' ')+1);
53 } catch (NumberFormatException nfe) {
58 public String toString() { return "SMTP " + code + ": " + message; }
59 public String getMessage() { return toString(); }
62 // Server //////////////////////////////////////////////////////////////////////////////
64 public static class Server {
65 public void handleRequest(Connection conn) {
66 conn.setTimeout(5 * 60 * 1000);
67 conn.setNewline("\r\n");
68 conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
70 Vector to = new Vector();
72 String remotehost = null;
73 for(String command = conn.readln(); ; command = conn.readln()) try {
74 if (command == null) return;
75 Log.warn(conn.getRemoteAddress()+"", command);
76 String c = command.toUpperCase();
77 if (c.startsWith("HELO")) {
78 remotehost = c.substring(5).trim();
79 conn.println("250 HELO " + conn.vhost);
80 from = null; to = new Vector();
81 } else if (c.startsWith("EHLO")) {
82 remotehost = c.substring(5).trim();
83 conn.println("250 "+conn.vhost+" greets " + remotehost);
85 from = null; to = new Vector();
86 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
87 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
88 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
89 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
90 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
91 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
92 } else if (c.startsWith("MAIL FROM:")) {
93 command = command.substring(10).trim();
94 from = command.equals("<>") ? null : new Address(command);
95 conn.println("250 " + from + " is syntactically correct");
96 } else if (c.startsWith("RCPT TO:")) {
97 // some clients are broken and put RCPT first; we will tolerate this
98 command = command.substring(8).trim();
99 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
100 Address addr = new Address(command);
101 if (addr.isLocal()) {
102 // FEATURE: should check the address further and give 550 if undeliverable
103 conn.println("250 " + addr + " is on this machine; I will deliver it");
105 } else if (conn.getRemoteAddress().isLoopbackAddress()) {
106 conn.println("250 you are connected locally, so I will let you send");
109 conn.println("551 sorry, " + addr + " is not on this machine");
111 } else if (c.startsWith("DATA")) {
112 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
113 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
114 conn.println("354 Enter message, ending with \".\" on a line by itself");
117 StringBuffer buf = new StringBuffer();
118 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
119 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
121 // FIXME: this is leaking BCC addrs
122 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
123 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
125 String s = conn.readln();
126 if (s == null) throw new RuntimeException("connection closed");
127 if (s.equals(".")) break;
128 if (s.startsWith(".")) s = s.substring(1);
129 buf.append(s + "\r\n");
131 String body = buf.toString();
133 for(int i=0; i<to.size(); i++) {
134 m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
137 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
138 conn.println("250 message accepted");
140 from = null; to = new Vector();
141 } catch (Reject.RejectException re) {
142 Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary());
143 conn.println("501 " + re.reason);
144 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
145 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
146 } catch (Later.LaterException le) { conn.println("453 try again later");
147 } catch (IOException ioe) {
148 //conn.println("554 " + ioe.toString());
149 Log.error(this, ioe);
153 } else { conn.println("500 unrecognized command"); }
154 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
159 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
161 public static class Outgoing extends Thread {
163 private static final HashSet deadHosts = new HashSet();
164 public static void accept(Message m) throws IOException {
165 if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
166 String traces = m.headers.get("Received");
169 for(int i=0; i<traces.length(); i++)
170 if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
172 if (lines > 100) { // required by rfc
173 Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
177 synchronized(Outgoing.class) {
179 Outgoing.class.notifyAll();
183 public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
184 public static boolean attempt(Message m, boolean noBounces) throws IOException {
185 if (m.envelopeTo == null) {
186 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
189 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
190 if (mx.length == 0) {
192 accept(m.bounce("could not resolve " + m.envelopeTo.host));
195 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
199 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
201 accept(m.bounce("could not send for 5 days"));
204 Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
208 for(int i=0; i<mx.length; i++) {
209 //if (deadHosts.contains(mx[i])) continue;
210 if (attempt(m, mx[i])) { return true; }
215 private static void check(String s, Connection conn) {
217 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
218 if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
220 private static boolean attempt(final Message m, final InetAddress mx) {
221 boolean accepted = false;
222 Connection conn = null;
224 Log.note("connecting to " + mx + "...");
225 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
226 conn.setNewline("\r\n");
227 conn.setTimeout(60 * 1000);
228 Log.note(" connected");
229 check(conn.readln(), conn); // banner
231 conn.println("EHLO " + conn.vhost);
232 check(conn.readln(), conn);
233 } catch (SMTPException smtpe) {
234 conn.println("HELO " + conn.vhost);
235 check(conn.readln(), conn);
237 if (m.envelopeFrom==null) {
238 Log.warn("", "MAIL FROM:<>");
239 conn.println("MAIL FROM:<>"); check(conn.readln(), conn);
241 Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
242 conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">"); check(conn.readln(), conn);
244 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
245 conn.println("DATA"); check(conn.readln(), conn);
246 Headers head = m.headers;
247 head.remove("return-path");
249 Stream stream = head.getStream();
250 for(String s = stream.readln(); s!=null; s=stream.readln()) {
251 if (s.startsWith(".")) conn.print(".");
255 stream = m.getBody().getStream();
256 for(String s = stream.readln(); s!=null; s=stream.readln()) {
257 if (s.startsWith(".")) conn.print(".");
261 String resp = conn.readln();
263 throw new SMTPException("server " + mx + " closed connection without accepting message");
265 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
268 } catch (SMTPException e) {
269 if (accepted) return true;
270 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
271 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
272 Log.warn(SMTP.Outgoing.class, e);
273 if (e.code >= 500 && e.code <= 599) {
275 attempt(m.bounce("unable to deliver: " + e), true);
276 } catch (Exception ex) {
277 Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
278 Log.error(SMTP.Outgoing.class, ex);
283 } catch (Exception e) {
284 if (accepted) return true;
285 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
286 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
287 Log.warn(SMTP.Outgoing.class, e);
288 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
291 if (conn != null) conn.close();
296 private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
297 private static int serials = 1;
298 private int serial = serials++;
299 private Mailbox.Iterator it;
302 synchronized(Outgoing.class) {
308 int count = spool.count(Query.all());
309 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
312 boolean good = false;
313 synchronized(Outgoing.class) {
314 it = spool.iterator();
315 OUTER: for(; it.next(); ) {
316 for(Outgoing o : threads)
317 if (o!=this && o.it != null && o.it.uid()==it.uid())
325 if (attempt(it.cur())) it.delete();
326 } catch (Exception e) {
327 Log.error(SMTP.Outgoing.class, e);
329 Log.info(this, "sleeping for 3s...");
332 } catch (Exception e) {
333 //if (e instanceof InterruptedException) throw e;
334 Log.error(SMTP.Outgoing.class, e);
336 Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
343 Log.setThreadAnnotation("[outgoing #"+serial+"] ");
346 synchronized(Outgoing.class) {
347 Outgoing.class.wait(5 * 60 * 1000);
350 } catch (InterruptedException e) { Log.warn(this, e); }
354 public static InetAddress[] getMailExchangerIPs(String hostName) {
357 Hashtable env = new Hashtable();
358 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
359 DirContext ictx = new InitialDirContext(env);
360 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
361 Attribute attr = attrs.get("MX");
363 ret = new InetAddress[1];
365 ret[0] = InetAddress.getByName(hostName);
367 } catch (UnknownHostException uhe) {
368 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
369 return new InetAddress[0];
372 ret = new InetAddress[attr.size()];
373 NamingEnumeration ne = attr.getAll();
374 for(int i=0; ne.hasMore();) {
375 String mx = (String)ne.next();
376 // FIXME we should be sorting here
377 mx = mx.substring(mx.indexOf(" ") + 1);
378 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
379 InetAddress ia = InetAddress.getByName(mx);
380 if (ia.equals(IP.getIP(127,0,0,1))) continue;
384 } catch (Exception e) {
385 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
386 Log.warn(SMTP.class, e);
387 return new InetAddress[0];