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: bounce messages (must go to return-path unless empty, in which case do not send
19 // FIXME: if more than 100 "Received" lines, must drop message
20 // FEATURE: infer messageid, date, if not present (?)
21 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
22 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
23 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
24 // FEATURE: exponential backoff on retry time?
25 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
28 public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
29 private static final Mailbox spool =
30 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
32 static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
34 public static void accept(Message m) throws IOException {
35 if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
36 else Target.root.accept(m);
39 public static class SMTPException extends MailException {
42 public SMTPException(String s) {
44 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
45 message = s.substring(s.indexOf(' ')+1);
46 } catch (NumberFormatException nfe) {
51 public String toString() { return "SMTP " + code + ": " + message; }
52 public String getMessage() { return toString(); }
55 // Server //////////////////////////////////////////////////////////////////////////////
57 public static class Server {
58 public void handleRequest(Connection conn) {
59 conn.setTimeout(5 * 60 * 1000);
60 conn.setNewline("\r\n");
61 conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
63 Vector to = new Vector();
65 String remotehost = null;
66 for(String command = conn.readln(); ; command = conn.readln()) try {
67 if (command == null) return;
68 String c = command.toUpperCase();
69 if (c.startsWith("HELO")) {
70 remotehost = c.substring(5).trim();
71 conn.println("250 HELO " + conn.vhost);
72 from = null; to = new Vector();
73 } else if (c.startsWith("EHLO")) {
74 remotehost = c.substring(5).trim();
77 from = null; to = new Vector();
78 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
79 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
80 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
81 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
82 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
83 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
84 } else if (c.startsWith("MAIL FROM:")) {
85 command = command.substring(10).trim();
86 from = command.equals("<>") ? null : new Address(command);
87 conn.println("250 " + from + " is syntactically correct");
88 } else if (c.startsWith("RCPT TO:")) {
89 // some clients are broken and put RCPT first; we will tolerate this
90 command = command.substring(8).trim();
91 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
92 Address addr = new Address(command);
94 // FEATURE: should check the address further and give 550 if undeliverable
95 conn.println("250 " + addr + " is on this machine; I will deliver it");
97 } else if (conn.getRemoteAddress().isLoopbackAddress()) {
98 conn.println("250 you are connected locally, so I will let you send");
101 conn.println("551 sorry, " + addr + " is not on this machine");
103 } else if (c.startsWith("DATA")) {
104 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
105 if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
106 conn.println("354 Enter message, ending with \".\" on a line by itself");
109 StringBuffer buf = new StringBuffer();
110 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
111 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
113 // FIXME: this is leaking BCC addrs
114 // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
115 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
117 String s = conn.readln();
118 if (s == null) throw new RuntimeException("connection closed");
119 if (s.equals(".")) break;
120 if (s.startsWith(".")) s = s.substring(1);
121 buf.append(s + "\r\n");
123 String body = buf.toString();
125 for(int i=0; i<to.size(); i++) {
126 m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
129 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
130 conn.println("250 message accepted");
132 from = null; to = new Vector();
133 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
134 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
135 } catch (Later.LaterException le) { conn.println("453 try again later");
136 } catch (IOException ioe) {
137 //conn.println("554 " + ioe.toString());
138 Log.error(this, ioe);
142 } else { conn.println("500 unrecognized command"); }
143 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
148 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
150 public static class Outgoing {
152 private static final HashSet deadHosts = new HashSet();
153 public static void accept(Message m) throws IOException {
154 if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
155 //Log.info(SMTP.class, "queued: " + m.summary());
157 if (m.traces.length >= 100)
158 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
160 else synchronized(Outgoing.class) {
162 Outgoing.class.notify();
166 public static boolean attempt(Message m) throws IOException {
167 if (m.envelopeTo == null) {
168 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
171 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
172 if (mx.length == 0) {
173 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
174 accept(m.bounce("could not resolve " + m.envelopeTo.host));
177 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
178 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
179 accept(m.bounce("could not send for 5 days"));
182 for(int i=0; i<mx.length; i++) {
183 if (deadHosts.contains(mx[i])) continue;
184 if (attempt(m, mx[i])) { return true; }
189 private static void check(String s, Connection conn) {
191 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
192 if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
194 private static boolean attempt(final Message m, final InetAddress mx) {
195 boolean accepted = false;
196 Connection conn = null;
198 Log.note("connecting to " + mx + "...");
199 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
200 conn.setNewline("\r\n");
201 conn.setTimeout(60 * 1000);
202 Log.note(" connected");
203 check(conn.readln(), conn); // banner
205 conn.println("EHLO " + conn.vhost);
206 check(conn.readln(), conn);
207 } catch (SMTPException smtpe) {
208 conn.println("HELO " + conn.vhost);
209 check(conn.readln(), conn);
211 if (m.envelopeFrom==null) {
212 Log.warn("", "MAIL FROM:<>");
213 conn.println("MAIL FROM:<>"); check(conn.readln(), conn);
215 Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
216 conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">"); check(conn.readln(), conn);
218 conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn);
219 conn.println("DATA"); check(conn.readln(), conn);
220 Headers head = m.headers;
221 head.remove("return-path");
223 Stream stream = head.getStream();
224 for(String s = stream.readln(); s!=null; s=stream.readln()) {
225 if (s.startsWith(".")) conn.print(".");
229 //Log.warn("***","");
231 stream = m.getBody().getStream();
232 for(String s = stream.readln(); s!=null; s=stream.readln()) {
233 if (s.startsWith(".")) conn.print(".");
238 String resp = conn.readln();
240 throw new SMTPException("server " + mx + " closed connection without accepting message");
242 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
245 } catch (Exception e) {
246 if (accepted) return true;
247 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
248 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
249 Log.warn(SMTP.Outgoing.class, e);
250 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
253 if (conn != null) conn.close();
260 Log.setThreadAnnotation("[outgoing smtp] ");
261 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
263 if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
264 for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
266 if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
267 if (attempt(it.cur())) it.delete();
268 } catch (Exception e) {
269 if (e instanceof InterruptedException) throw e;
270 Log.error(SMTP.Outgoing.class, e);
273 synchronized(Outgoing.class) {
274 if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
275 Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
276 Outgoing.class.wait(5 * 60 * 1000);
278 Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
281 } catch (Exception e) {
282 Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e);
283 Log.error(SMTP.Outgoing.class, e);
288 public static InetAddress[] getMailExchangerIPs(String hostName) {
291 Hashtable env = new Hashtable();
292 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
293 DirContext ictx = new InitialDirContext(env);
294 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
295 Attribute attr = attrs.get("MX");
297 ret = new InetAddress[1];
299 ret[0] = InetAddress.getByName(hostName);
301 } catch (UnknownHostException uhe) {
302 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
303 return new InetAddress[0];
306 ret = new InetAddress[attr.size()];
307 NamingEnumeration ne = attr.getAll();
308 for(int i=0; ne.hasMore();) {
309 String mx = (String)ne.next();
310 // FIXME we should be sorting here
311 mx = mx.substring(mx.indexOf(" ") + 1);
312 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
313 InetAddress ia = InetAddress.getByName(mx);
314 if (ia.equals(IP.getIP(127,0,0,1))) continue;
318 } catch (Exception e) {
319 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
320 Log.warn(SMTP.class, e);
321 return new InetAddress[0];