1 package org.ibex.mail.protocol;
2 import org.ibex.mail.*;
3 import org.ibex.mail.target.*;
4 import org.ibex.jinetd.Worker;
5 import org.ibex.util.*;
11 import javax.naming.*;
12 import javax.naming.directory.*;
14 // FEATURE: exponential backoff on retry time?
17 private static final Mailbox spool =
18 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
20 static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
22 // Server //////////////////////////////////////////////////////////////////////////////
24 public static class Server implements Worker {
25 public void handleRequest(Connection conn) {
26 Log.error(this, "accepted...");
27 conn.setTimeout(5 * 60 * 1000);
28 conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
30 Vector to = new Vector();
31 for(String command = conn.readln(); ; command = conn.readln()) try {
32 if (command == null) return;
33 String c = command.toUpperCase();
34 if (c.startsWith("HELO")) { conn.println("250 HELO " + conn.vhost); from = null; to = new Vector();
35 } else if (c.startsWith("EHLO")) { conn.println("250"); from = null; to = new Vector();
36 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
37 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
38 } else if (c.startsWith("VRFY")) { conn.println("252 We don't VRFY; proceed anyway");
39 } else if (c.startsWith("EXPN")) { conn.println("550 EXPN not available");
40 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
41 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
42 } else if (c.startsWith("MAIL FROM:")) {
43 conn.println("250 " + (from = new Address(command.substring(10).trim())) + " is syntactically correct");
44 } else if (c.startsWith("RCPT TO:")) {
45 if (from == null) { conn.println("503 MAIL FROM must precede RCPT TO"); continue; }
46 command = command.substring(8).trim();
47 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
48 Address addr = new Address(command);
49 if (addr.isLocal()) conn.println("250 " + addr + " is on this machine; I will deliver it");
50 else if (conn.getRemoteAddress().isLoopbackAddress())
51 conn.println("250 you are connected locally, so I will let you send");
52 else { conn.println("551 sorry, " + addr + " is not on this machine"); }
54 } else if (c.startsWith("DATA")) {
55 if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
56 if (to == null) { conn.println("503 RCPT TO command must precede DATA"); continue; }
57 conn.println("354 Enter message, ending with \".\" on a line by itself");
60 StringBuffer buf = new StringBuffer();
62 String s = conn.readln();
63 if (s == null) throw new RuntimeException("connection closed");
64 if (s.equals(".")) break;
65 if (s.startsWith(".")) s = s.substring(1);
66 buf.append(s + "\r\n");
68 String body = buf.toString();
70 for(int i=0; i<to.size(); i++) {
71 m = new Message(new Stream(body), new Message.Envelope(from, (Address)to.elementAt(i), new Date()));
72 if (!m.envelope.to.isLocal()) Outgoing.accept(m);
73 else Target.root.accept(m);
75 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
76 conn.println("250 message accepted");
78 from = null; to = new Vector();
79 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
80 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
81 } catch (IOException ioe) { conn.println("554 " + ioe.toString());
83 } else { conn.println("500 unrecognized command"); }
84 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); /* FIXME could be wrong code */ }
89 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
91 public static class Outgoing {
93 private static final HashSet deadHosts = new HashSet();
94 public static void accept(Message m) throws IOException {
95 if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
96 Log.info(SMTP.class, "queued:\n" + m.summary());
97 if (m.traces.length >= 100)
98 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
99 else synchronized(Outgoing.class) {
101 Outgoing.class.notify();
105 public static boolean attempt(Message m) throws IOException {
106 InetAddress[] mx = getMailExchangerIPs(m.envelope.to.host);
107 if (mx.length == 0) {
108 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelope.to.host + "; bouncing it\n" + m.summary());
109 accept(m.bounce("could not resolve " + m.envelope.to.host));
112 if (new Date().getTime() - m.envelope.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
113 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
114 accept(m.bounce("could not send for 5 days"));
117 for(int i=0; i<mx.length; i++) {
118 if (deadHosts.contains(mx[i])) continue;
119 if (attempt(m, mx[i])) { return true; }
124 private static void check(String s, Connection conn) {
125 while (s.charAt(3) == '-') s = conn.readln();
126 if (s.startsWith("4")||s.startsWith("5")) throw new MailException(s);
128 private static boolean attempt(final Message m, final InetAddress mx) {
129 boolean accepted = false;
130 Connection conn = null;
132 Log.info(SMTP.Outgoing.class, "connecting to " + mx + "...");
133 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
134 conn.setTimeout(60 * 1000);
135 Log.info(SMTP.Outgoing.class, "connected");
136 check(conn.readln(), conn); // banner
137 conn.println("HELO " + conn.vhost); check(conn.readln(), conn);
138 conn.println("MAIL FROM:<" + m.envelope.from.user + "@" + m.envelope.from.host+">"); check(conn.readln(), conn);
139 conn.println("RCPT TO:<" + m.envelope.to.user + "@" + m.envelope.to.host+">"); check(conn.readln(), conn);
140 conn.println("DATA"); check(conn.readln(), conn);
141 conn.println(m.toString());
143 check(conn.readln(), conn);
144 Log.info(SMTP.Outgoing.class, "success: message accepted by " + mx);
147 } catch (Exception e) {
148 if (accepted) return true;
149 Log.warn(SMTP.Outgoing.class, "unable to send; error=" + e);
150 Log.warn(SMTP.Outgoing.class, e);
153 if (conn != null) conn.close();
160 Log.setThreadAnnotation("[outgoing smtp] ");
161 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
163 for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
164 try { if (attempt(it.cur())) it.delete(); }
165 catch (Exception e) { Log.error(SMTP.Outgoing.class, e); }
167 synchronized(Outgoing.class) {
168 Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
169 Outgoing.class.wait(5 * 60 * 1000);
171 Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
174 } catch (Exception e) { Log.error(SMTP.Outgoing.class, e); }
178 public static InetAddress[] getMailExchangerIPs(String hostName) {
181 Hashtable env = new Hashtable();
182 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
183 DirContext ictx = new InitialDirContext(env);
184 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
185 Attribute attr = attrs.get("MX");
187 ret = new InetAddress[1];
189 ret[0] = InetAddress.getByName(hostName);
191 } catch (UnknownHostException uhe) {
192 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
193 return new InetAddress[0];
196 ret = new InetAddress[attr.size()];
197 NamingEnumeration ne = attr.getAll();
198 for(int i=0; ne.hasMore(); i++) {
199 String mx = (String)ne.next();
200 // FIXME we should be sorting here
201 mx = mx.substring(mx.indexOf(" ") + 1);
202 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
203 ret[i] = InetAddress.getByName(mx);
206 } catch (Exception e) {
207 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
208 Log.warn(SMTP.class, e);
209 return new InetAddress[0];