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 public static class SMTPException extends MailException {
25 public SMTPException(String s) {
26 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
27 message = s.substring(s.indexOf(' ')+1);
29 public String toString() { return "SMTP " + code + ": " + message; }
30 public String getMessage() { return toString(); }
33 // Server //////////////////////////////////////////////////////////////////////////////
35 public static class Server implements Worker {
36 public void handleRequest(Connection conn) {
37 conn.setTimeout(5 * 60 * 1000);
38 conn.setNewline("\r\n");
39 conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
41 Vector to = new Vector();
42 for(String command = conn.readln(); ; command = conn.readln()) try {
43 if (command == null) return;
44 String c = command.toUpperCase();
45 if (c.startsWith("HELO")) { conn.println("250 HELO " + conn.vhost); from = null; to = new Vector();
46 } else if (c.startsWith("EHLO")) { conn.println("250"); from = null; to = new Vector();
47 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
48 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
49 } else if (c.startsWith("VRFY")) { conn.println("252 We don't VRFY; proceed anyway");
50 } else if (c.startsWith("EXPN")) { conn.println("550 EXPN not available");
51 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
52 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
53 } else if (c.startsWith("MAIL FROM:")) {
54 command = command.substring(10).trim();
55 from = command.equals("<>") ? null : new Address(command);
56 conn.println("250 " + from + " is syntactically correct");
57 } else if (c.startsWith("RCPT TO:")) {
58 //if (from == null) { conn.println("503 MAIL FROM must precede RCPT TO"); continue; }
59 command = command.substring(8).trim();
60 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
61 Address addr = new Address(command);
62 if (addr.isLocal()) conn.println("250 " + addr + " is on this machine; I will deliver it");
63 else if (conn.getRemoteAddress().isLoopbackAddress())
64 conn.println("250 you are connected locally, so I will let you send");
65 else { conn.println("551 sorry, " + addr + " is not on this machine"); }
67 } else if (c.startsWith("DATA")) {
68 if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
69 if (to == null) { conn.println("503 RCPT TO command must precede DATA"); continue; }
70 conn.println("354 Enter message, ending with \".\" on a line by itself");
73 StringBuffer buf = new StringBuffer();
75 String s = conn.readln();
76 if (s == null) throw new RuntimeException("connection closed");
77 if (s.equals(".")) break;
78 if (s.startsWith(".")) s = s.substring(1);
79 buf.append(s + "\r\n");
81 String body = buf.toString();
83 for(int i=0; i<to.size(); i++) {
84 m = Message.newMessage(new Stream(body), from, (Address)to.elementAt(i));
85 if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
86 else Target.root.accept(m);
88 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
89 conn.println("250 message accepted");
91 from = null; to = new Vector();
92 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
93 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
94 } catch (IOException ioe) {
95 //conn.println("554 " + ioe.toString());
100 } else { conn.println("500 unrecognized command"); }
101 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
106 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
108 public static class Outgoing {
110 private static final HashSet deadHosts = new HashSet();
111 public static void accept(Message m) throws IOException {
112 if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
113 //Log.info(SMTP.class, "queued: " + m.summary());
114 if (m.traces.length >= 100)
115 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
116 else synchronized(Outgoing.class) {
118 Outgoing.class.notify();
122 public static boolean attempt(Message m) throws IOException {
123 InetAddress[] mx = getMailExchangerIPs(m.envelope.to.host);
124 if (mx.length == 0) {
125 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
126 accept(m.bounce("could not resolve " + m.envelopeTo.host));
129 if (new Date().getTime() - m.envelope.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
130 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
131 accept(m.bounce("could not send for 5 days"));
134 for(int i=0; i<mx.length; i++) {
135 if (deadHosts.contains(mx[i])) continue;
136 if (attempt(m, mx[i])) { return true; }
141 private static void check(String s, Connection conn) {
142 while (s.charAt(3) == '-') s = conn.readln();
143 if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
145 private static boolean attempt(final Message m, final InetAddress mx) {
146 boolean accepted = false;
147 Connection conn = null;
149 Log.note("connecting to " + mx + "...");
150 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
151 conn.setNewline("\r\n");
152 conn.setTimeout(60 * 1000);
153 Log.note(" connected");
154 check(conn.readln(), conn); // banner
155 conn.println("HELO " + conn.vhost); check(conn.readln(), conn);
156 conn.println("MAIL FROM:<" + m.envelope.from.user + "@" + m.envelope.from.host+">"); check(conn.readln(), conn);
157 conn.println("RCPT TO:<" + m.envelope.to.user + "@" + m.envelope.to.host+">"); check(conn.readln(), conn);
158 conn.println("DATA"); check(conn.readln(), conn);
159 conn.println(m.toString());
161 check(conn.readln(), conn);
162 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary());
165 } catch (Exception e) {
166 if (accepted) return true;
167 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
168 Log.warn(SMTP.Outgoing.class, e);
171 if (conn != null) conn.close();
178 Log.setThreadAnnotation("[outgoing smtp] ");
179 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
181 if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
182 for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
184 if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
185 if (attempt(it.cur())) it.delete();
186 } catch (Exception e) {
187 if (e instanceof InterruptedException) throw e;
188 Log.error(SMTP.Outgoing.class, e);
191 synchronized(Outgoing.class) {
192 if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
193 Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
194 Outgoing.class.wait(5 * 60 * 1000);
196 Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
199 } catch (Exception e) {
200 Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e);
201 Log.error(SMTP.Outgoing.class, e);
206 public static InetAddress[] getMailExchangerIPs(String hostName) {
209 Hashtable env = new Hashtable();
210 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
211 DirContext ictx = new InitialDirContext(env);
212 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
213 Attribute attr = attrs.get("MX");
215 ret = new InetAddress[1];
217 ret[0] = InetAddress.getByName(hostName);
219 } catch (UnknownHostException uhe) {
220 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
221 return new InetAddress[0];
224 ret = new InetAddress[attr.size()];
225 NamingEnumeration ne = attr.getAll();
226 for(int i=0; ne.hasMore(); i++) {
227 String mx = (String)ne.next();
228 // FIXME we should be sorting here
229 mx = mx.substring(mx.indexOf(" ") + 1);
230 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
231 ret[i] = InetAddress.getByName(mx);
234 } catch (Exception e) {
235 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
236 Log.warn(SMTP.class, e);
237 return new InetAddress[0];