1 package org.ibex.mail.protocol;
2 import org.ibex.mail.*;
3 import org.ibex.mail.target.*;
4 import org.ibex.util.*;
10 import javax.naming.directory.*;
12 // FEATURE: exponential backoff on retry time?
15 private static final Mailbox spool =
16 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT, false).slash("spool", true).slash("smtp", true);
17 static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
19 // Server //////////////////////////////////////////////////////////////////////////////
21 public static class Server extends Connection {
22 public Server(Socket conn, String vhost) throws IOException { super(conn, vhost); }
23 public Server(com.caucho.server.connection.Connection conn) throws IOException { super(new SMTP(), conn); }
24 public boolean handle_() throws IOException, MailException {
25 setSoTimeout(5 * 60 * 1000);
26 println("220 " + vhost + " SMTP " + this.getClass().getName());
28 Vector to = new Vector();
29 for(String command = readln(); ; command = readln()) {
30 String c = command.toUpperCase();
31 if (c.startsWith("HELO")) { println("250 HELO " + vhost); from = null; to = new Vector();
32 } else if (c.startsWith("EHLO")) { println("250"); from = null; to = new Vector();
33 } else if (c.startsWith("RSET")) { println("250 reset ok"); from = null; to = new Vector();
34 } else if (c.startsWith("HELP")) { println("214 you are beyond help. see a trained professional.");
35 } else if (c.startsWith("VRFY")) { println("252 We don't VRFY; proceed anyway");
36 } else if (c.startsWith("EXPN")) { println("550 EXPN not available");
37 } else if (c.startsWith("NOOP")) { println("250 OK");
38 } else if (c.startsWith("QUIT")) { println("221 " + vhost + " closing connection"); return false;
39 } else if (c.startsWith("MAIL FROM:")) {
40 println("250 " + (from = new Address(command.substring(10).trim())) + " is syntactically correct");
41 } else if (c.startsWith("RCPT TO:")) {
42 if (from == null) { println("503 MAIL FROM must precede RCPT TO"); continue; }
43 command = command.substring(8).trim();
44 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
45 Address addr = new Address(command);
46 InetAddress[] mx = getMailExchangerIPs(addr.host);
48 if (((InetSocketAddress)conn.getRemoteSocketAddress()).getAddress().isLoopbackAddress()) {
49 println("250 you are connected locally, so I will let you send");
52 for(int i=0; !good && i<mx.length; i++) if (NetworkInterface.getByInetAddress(mx[i]) != null) good = true;
53 if (!good) { println("551 sorry, " + addr + " is not on this machine"); return false; }
54 println("250 " + addr + " is on this machine; I will deliver it");
56 } else if (c.startsWith("DATA")) {
57 if (from == null) { println("503 MAIL FROM command must precede DATA"); continue; }
58 if (to == null) { println("503 RCPT TO command must precede DATA"); continue; }
59 println("354 Enter message, ending with \".\" on a line by itself");
61 for(int i=0; i<to.size(); i++)
62 Target.root.accept(new Message(from, (Address)to.elementAt(i), new DotTerminatedLineReader(lr)));
63 println("250 message accepted");
64 } catch (MailException.Malformed mfe) { println("501 " + mfe.toString());
65 } catch (MailException.MailboxFull mbf) { println("452 " + mbf);
66 } catch (IOException ioe) { println("554 " + ioe.toString());
69 } else { println("500 unrecognized command"); }
75 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
77 public static class Outgoing {
78 private static final HashSet deadHosts = new HashSet();
79 public static void send(Message m) throws IOException {
80 if (m.traces.length >= 100)
81 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
82 else synchronized(Outgoing.class) {
84 Outgoing.class.notify();
88 private static boolean attempt(Message m) throws IOException {
89 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
91 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
92 send(m.bounce("could not resolve " + m.envelopeTo.host));
95 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
96 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
97 send(m.bounce("could not send for 5 days"));
100 for(int i=0; i<mx.length; i++) {
101 if (deadHosts.contains(mx[i])) continue;
102 if (attempt(m, mx[i])) { return true; }
107 private static void check(String s) { if (s.startsWith("4")||s.startsWith("5")) throw new MailException(s); }
108 private static boolean attempt(final Message m, final InetAddress mx) {
109 boolean accepted0 = false;
111 Log.info(SMTP.Outgoing.class, "connecting...");
112 accepted0 = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName()) {
113 public boolean handleRequest() throws IOException {
114 Log.info(SMTP.Outgoing.class, "connected");
115 check(readln()); // banner
116 println("HELO " + vhost ); check(readln());
117 println("MAIL FROM: " + m.envelopeFrom); check(readln());
118 println("RCPT TO: " + m.envelopeTo); check(readln());
119 println("DATA"); check(readln());
123 Log.info(SMTP.Outgoing.class, "message accepted by " + mx);
124 boolean accepted = true;
133 } catch (Exception e) {
134 if (accepted0) return true;
135 Log.warn(SMTP.Outgoing.class, "unable to send; error=" + e);
136 Log.warn(SMTP.Outgoing.class, e);
138 } finally { Log.setThreadAnnotation("[outgoing smtp] "); }
143 Log.setThreadAnnotation("[outgoing smtp] ");
144 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
146 for(Mailbox.Iterator it = spool.iterator(); it.next(); )
147 try { if (attempt(it.cur())) it.delete(); }
148 catch (IOException e) { Log.error(SMTP.Outgoing.class, e); }
149 synchronized(Outgoing.class) {
150 Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
151 Outgoing.class.wait(10 * 60 * 1000);
153 Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
156 } catch (Exception e) { Log.error(SMTP.Outgoing.class, e); }
160 public static InetAddress[] getMailExchangerIPs(String hostName) {
163 Hashtable env = new Hashtable();
164 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
165 DirContext ictx = new InitialDirContext(env);
166 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
167 Attribute attr = attrs.get("MX");
169 ret = new InetAddress[1];
171 ret[0] = InetAddress.getByName(hostName);
173 } catch (UnknownHostException uhe) {
174 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
175 return new InetAddress[0];
178 ret = new InetAddress[attr.size()];
179 NamingEnumeration ne = attr.getAll();
180 for(int i=0; ne.hasMore(); i++) {
181 String mx = (String)ne.next();
182 // FIXME we should be sorting here
183 mx = mx.substring(mx.indexOf(" ") + 1);
184 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
185 ret[i] = InetAddress.getByName(mx);
188 } catch (Exception e) {
189 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
190 Log.warn(SMTP.class, e);
191 return new InetAddress[0];
197 // Helpers //////////////////////////////////////////////////////////////////////////////
199 public static class DotTerminatedLineReader extends LineReader {
200 private final LineReader r;
201 private boolean done = false;
202 public DotTerminatedLineReader(LineReader r) { super(null); this.r = r; }
203 public String readLine() throws IOException {
204 if (done) return null;
205 String s = r.readLine();
206 if (s.equals(".")) { done = true; return null; }
207 if (s.startsWith(".")) return s.substring(1);