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.*;
14 import javax.naming.*;
15 import javax.naming.directory.*;
17 // FIXME: bounce messages (must go to return-path unless empty, in which case do not send
18 // FIXME: if more than 100 "Received" lines, must drop message
19 // FEATURE: infer messageid, date, if not present (?)
20 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
21 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
22 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
23 // FEATURE: exponential backoff on retry time?
24 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
27 public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
28 private static final Mailbox spool =
29 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
31 static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
33 public static void accept(Message m) throws IOException {
34 if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
35 else Target.root.accept(m);
38 public static class SMTPException extends MailException {
41 public SMTPException(String s) {
42 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
43 message = s.substring(s.indexOf(' ')+1);
45 public String toString() { return "SMTP " + code + ": " + message; }
46 public String getMessage() { return toString(); }
49 // Server //////////////////////////////////////////////////////////////////////////////
51 public static class Server {
52 public void handleRequest(Connection conn) {
53 conn.setTimeout(5 * 60 * 1000);
54 conn.setNewline("\r\n");
55 conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
57 Vector to = new Vector();
59 String remotehost = null;
60 for(String command = conn.readln(); ; command = conn.readln()) try {
61 if (command == null) return;
62 String c = command.toUpperCase();
63 if (c.startsWith("HELO")) {
64 remotehost = c.substring(5).trim();
65 conn.println("250 HELO " + conn.vhost);
66 from = null; to = new Vector();
67 } else if (c.startsWith("EHLO")) {
68 remotehost = c.substring(5).trim();
71 from = null; to = new Vector();
72 } else if (c.startsWith("RSET")) { conn.println("250 reset ok"); from = null; to = new Vector();
73 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help. see a trained professional.");
74 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
75 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
76 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
77 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
78 } else if (c.startsWith("MAIL FROM:")) {
79 command = command.substring(10).trim();
80 from = command.equals("<>") ? null : new Address(command);
81 conn.println("250 " + from + " is syntactically correct");
82 } else if (c.startsWith("RCPT TO:")) {
83 // some clients are broken and put RCPT first; we will tolerate this
84 command = command.substring(8).trim();
85 if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
86 Address addr = new Address(command);
88 // FEATURE: should check the address further and give 550 if undeliverable
89 conn.println("250 " + addr + " is on this machine; I will deliver it");
90 } else if (conn.getRemoteAddress().isLoopbackAddress())
91 conn.println("250 you are connected locally, so I will let you send");
92 else { conn.println("551 sorry, " + addr + " is not on this machine"); }
94 } else if (c.startsWith("DATA")) {
95 //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
96 if (to == null) { conn.println("503 RCPT TO command must precede DATA"); continue; }
97 conn.println("354 Enter message, ending with \".\" on a line by itself");
100 StringBuffer buf = new StringBuffer();
101 buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
102 buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
103 buf.append(" for "); for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
104 buf.append("; " + dateFormat.format(new Date()) + "\r\n");
106 String s = conn.readln();
107 if (s == null) throw new RuntimeException("connection closed");
108 if (s.equals(".")) break;
109 if (s.startsWith(".")) s = s.substring(1);
110 buf.append(s + "\r\n");
112 String body = buf.toString();
114 for(int i=0; i<to.size(); i++) {
115 m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
118 if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
119 conn.println("250 message accepted");
121 from = null; to = new Vector();
122 } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
123 } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
124 } catch (Later.LaterException le) { conn.println("453 try again later");
125 } catch (IOException ioe) {
126 //conn.println("554 " + ioe.toString());
127 Log.error(this, ioe);
131 } else { conn.println("500 unrecognized command"); }
132 } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
137 // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
139 public static class Outgoing {
141 private static final HashSet deadHosts = new HashSet();
142 public static void accept(Message m) throws IOException {
143 if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
144 //Log.info(SMTP.class, "queued: " + m.summary());
146 if (m.traces.length >= 100)
147 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
149 else synchronized(Outgoing.class) {
151 Outgoing.class.notify();
155 public static boolean attempt(Message m) throws IOException {
156 if (m.envelopeTo == null) {
157 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
160 InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
161 if (mx.length == 0) {
162 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
163 accept(m.bounce("could not resolve " + m.envelopeTo.host));
166 if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
167 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
168 accept(m.bounce("could not send for 5 days"));
171 for(int i=0; i<mx.length; i++) {
172 if (deadHosts.contains(mx[i])) continue;
173 if (attempt(m, mx[i])) { return true; }
178 private static void check(String s, Connection conn) {
179 while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
180 if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
182 private static boolean attempt(final Message m, final InetAddress mx) {
183 boolean accepted = false;
184 Connection conn = null;
186 Log.note("connecting to " + mx + "...");
187 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
188 conn.setNewline("\r\n");
189 conn.setTimeout(60 * 1000);
190 Log.note(" connected");
191 check(conn.readln(), conn); // banner
193 conn.println("EHLO " + conn.vhost);
194 check(conn.readln(), conn);
195 } catch (SMTPException smtpe) {
196 conn.println("HELO " + conn.vhost);
197 check(conn.readln(), conn);
199 if (m.envelopeFrom==null) {
200 conn.println("MAIL FROM:<>"); check(conn.readln(), conn);
202 conn.println("MAIL FROM:<" + m.envelopeFrom.user + "@" + m.envelopeFrom.host+">"); check(conn.readln(), conn);
204 conn.println("RCPT TO:<" + m.envelopeTo.user + "@" + m.envelopeTo.host+">"); check(conn.readln(), conn);
205 conn.println("DATA"); check(conn.readln(), conn);
206 Stream stream = m.getStream();
207 boolean inheaders = true;
209 String s = stream.readln();
210 if (s == null) break;
211 if (s.length() == 0) inheaders = false;
212 // quash Return-Path; required by RFC2822
213 if (inheaders && s.toLowerCase().startsWith("Return-Path:")) continue;
214 if (s.startsWith(".")) conn.print(".");
218 check(conn.readln(), conn);
219 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary());
222 } catch (Exception e) {
223 if (accepted) return true;
224 Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e);
225 Log.warn(SMTP.Outgoing.class, " message: " + m.summary());
226 Log.warn(SMTP.Outgoing.class, e);
229 if (conn != null) conn.close();
236 Log.setThreadAnnotation("[outgoing smtp] ");
237 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
239 if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
240 for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
242 if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
243 if (attempt(it.cur())) it.delete();
244 } catch (Exception e) {
245 if (e instanceof InterruptedException) throw e;
246 Log.error(SMTP.Outgoing.class, e);
249 synchronized(Outgoing.class) {
250 if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
251 Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
252 Outgoing.class.wait(5 * 60 * 1000);
254 Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
257 } catch (Exception e) {
258 Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e);
259 Log.error(SMTP.Outgoing.class, e);
264 public static InetAddress[] getMailExchangerIPs(String hostName) {
267 Hashtable env = new Hashtable();
268 env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
269 DirContext ictx = new InitialDirContext(env);
270 Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
271 Attribute attr = attrs.get("MX");
273 ret = new InetAddress[1];
275 ret[0] = InetAddress.getByName(hostName);
277 } catch (UnknownHostException uhe) {
278 Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
279 return new InetAddress[0];
282 ret = new InetAddress[attr.size()];
283 NamingEnumeration ne = attr.getAll();
284 for(int i=0; ne.hasMore(); i++) {
285 String mx = (String)ne.next();
286 // FIXME we should be sorting here
287 mx = mx.substring(mx.indexOf(" ") + 1);
288 if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
289 ret[i] = InetAddress.getByName(mx);
292 } catch (Exception e) {
293 Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
294 Log.warn(SMTP.class, e);
295 return new InetAddress[0];