2fc51a3bc272a1b5943ce707256297a250b26805
[org.ibex.mail.git] / src / org / ibex / mail / protocol / SMTP.java
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.
4
5 package org.ibex.mail.protocol;
6 import org.ibex.mail.*;
7 import org.ibex.mail.target.*;
8 import org.ibex.jinetd.Worker;
9 import org.ibex.util.*;
10 import org.ibex.io.*;
11 import java.net.*;
12 import java.io.*;
13 import java.util.*;
14 import java.text.*;
15 import javax.naming.*;
16 import javax.naming.directory.*;
17
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
26 public class SMTP {
27
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);
31
32     static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
33
34     public static class SMTPException extends MailException {
35         int code;
36         String message;
37         public SMTPException(String s) {
38             code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
39             message = s.substring(s.indexOf(' ')+1);
40         }
41         public String toString() { return "SMTP " + code + ": " + message; }
42         public String getMessage() { return toString(); }
43     }
44
45     // Server //////////////////////////////////////////////////////////////////////////////
46
47     public static class Server implements Worker {
48         public void handleRequest(Connection conn) {
49             conn.setTimeout(5 * 60 * 1000);
50             conn.setNewline("\r\n");
51             conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
52             Address from = null;
53             Vector to = new Vector();
54             boolean ehlo = false;
55             String remotehost = null;
56             for(String command = conn.readln(); ; command = conn.readln()) try {
57                 if (command == null) return;
58                 String c = command.toUpperCase();
59                 if (c.startsWith("HELO"))        {
60                     remotehost = c.substring(5).trim();
61                     conn.println("250 HELO " + conn.vhost);
62                     from = null; to = new Vector();
63                 } else if (c.startsWith("EHLO")) {
64                     remotehost = c.substring(5).trim();
65                     conn.println("250");
66                     ehlo = true;     
67                     from = null; to = new Vector();
68                 } else if (c.startsWith("RSET")) { conn.println("250 reset ok");           from = null; to = new Vector();
69                 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help.  see a trained professional.");
70                 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
71                 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
72                 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
73                 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
74                 } else if (c.startsWith("MAIL FROM:")) {
75                     command = command.substring(10).trim();
76                     from = command.equals("<>") ? null : new Address(command);
77                     conn.println("250 " + from + " is syntactically correct");
78                 } else if (c.startsWith("RCPT TO:")) {
79                     // some clients are broken and put RCPT first; we will tolerate this
80                     command = command.substring(8).trim();
81                     if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
82                     Address addr = new Address(command);
83                     if (addr.isLocal()) {
84                         // FEATURE: should check the address further and give 550 if undeliverable
85                         conn.println("250 " + addr + " is on this machine; I will deliver it");
86                     } else if (conn.getRemoteAddress().isLoopbackAddress())
87                         conn.println("250 you are connected locally, so I will let you send");
88                     else { conn.println("551 sorry, " + addr + " is not on this machine"); }
89                     to.addElement(addr);
90                 } else if (c.startsWith("DATA")) {
91                     //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
92                     if (to == null) { conn.println("503 RCPT TO command must precede DATA"); continue; }
93                     conn.println("354 Enter message, ending with \".\" on a line by itself");
94                     conn.flush();
95                     try {
96                         StringBuffer buf = new StringBuffer();
97                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
98                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
99                         buf.append("          for "); for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
100                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
101                         while(true) {
102                             String s = conn.readln();
103                             if (s == null) throw new RuntimeException("connection closed");
104                             if (s.equals(".")) break;
105                             if (s.startsWith(".")) s = s.substring(1);
106                             buf.append(s + "\r\n");
107                         }
108                         String body = buf.toString();
109                         Message m = null;
110                         for(int i=0; i<to.size(); i++) {
111                             m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
112                             if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
113                             else                         Target.root.accept(m);
114                         }
115                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
116                         conn.println("250 message accepted");
117                         conn.flush();
118                         from = null; to = new Vector();
119                     } catch (MailException.Malformed mfe) {   conn.println("501 " + mfe.toString());
120                     } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
121                     } catch (Later.LaterException le) {       conn.println("453 try again later");
122                     } catch (IOException ioe) {               
123                         //conn.println("554 " + ioe.toString());
124                         Log.error(this, ioe);
125                         conn.close();
126                         return;
127                     }
128                 } else                    { conn.println("500 unrecognized command"); }                    
129             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
130         }
131     }
132
133
134     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
135
136     public static class Outgoing {
137
138         private static final HashSet deadHosts = new HashSet();
139         public static void accept(Message m) throws IOException {
140             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
141             //Log.info(SMTP.class, "queued: " + m.summary());
142             /*
143             if (m.traces.length >= 100)
144                 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
145             */
146             else synchronized(Outgoing.class) {
147                 spool.add(m);
148                 Outgoing.class.notify();
149             }
150         }
151
152         public static boolean attempt(Message m) throws IOException {
153             if (m.envelopeTo == null) {
154                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
155                 return false;
156             }
157             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
158             if (mx.length == 0) {
159                 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
160                 accept(m.bounce("could not resolve " + m.envelopeTo.host));
161                 return true;
162             }
163             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
164                 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
165                 accept(m.bounce("could not send for 5 days"));
166                 return true;
167             }
168             for(int i=0; i<mx.length; i++) {
169                 if (deadHosts.contains(mx[i])) continue;
170                 if (attempt(m, mx[i])) { return true; }
171             }
172             return false;
173         }
174
175         private static void check(String s, Connection conn) {
176             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
177             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
178         }
179         private static boolean attempt(final Message m, final InetAddress mx) {
180             boolean accepted = false;
181             Connection conn = null;
182             try {
183                 Log.note("connecting to " + mx + "...");
184                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
185                 conn.setNewline("\r\n");
186                 conn.setTimeout(60 * 1000);
187                 Log.note("    connected");
188                 check(conn.readln(), conn);  // banner
189                 try {
190                     conn.println("EHLO " + conn.vhost);
191                     check(conn.readln(), conn);
192                 } catch (SMTPException smtpe) {
193                     conn.println("HELO " + conn.vhost);
194                     check(conn.readln(), conn);
195                 }
196                 if (m.envelopeFrom==null) {
197                     conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
198                 } else {
199                     conn.println("MAIL FROM:<" + m.envelopeFrom.user + "@" + m.envelopeFrom.host+">");  check(conn.readln(), conn);
200                 }
201                 conn.println("RCPT TO:<"   + m.envelopeTo.user + "@" + m.envelopeTo.host+">");      check(conn.readln(), conn);
202                 conn.println("DATA");                          check(conn.readln(), conn);
203                 Stream stream = m.getStream();
204                 boolean inheaders = true;
205                 while(true) {
206                     String s = stream.readln();
207                     if (s == null) break;
208                     if (s.length() == 0) inheaders = false;
209                     // quash Return-Path; required by RFC2822
210                     if (inheaders && s.toLowerCase().startsWith("Return-Path:")) continue;
211                     if (s.startsWith(".")) conn.print(".");
212                     conn.println(s);
213                 }
214                 conn.println(".");
215                 check(conn.readln(), conn);
216                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary());
217                 accepted = true;
218                 conn.close();
219             } catch (Exception e) {
220                 if (accepted) return true;
221                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
222                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
223                 Log.warn(SMTP.Outgoing.class, e);
224                 return false;
225             } finally {
226                 if (conn != null) conn.close();
227             }
228             return accepted;
229         }
230
231         static void runq() {
232             try {
233                 Log.setThreadAnnotation("[outgoing smtp] ");
234                 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
235                 while(true) {
236                     if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
237                     for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
238                         try {
239                             if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
240                             if (attempt(it.cur())) it.delete();
241                         } catch (Exception e)   {
242                             if (e instanceof InterruptedException) throw e;
243                             Log.error(SMTP.Outgoing.class, e);
244                         }
245                     }
246                     synchronized(Outgoing.class) {
247                         if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
248                         Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
249                         Outgoing.class.wait(5 * 60 * 1000);
250                         deadHosts.clear();
251                         Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
252                     }
253                 }
254             } catch (Exception e) {
255                 Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e);
256                 Log.error(SMTP.Outgoing.class, e);
257             }
258         }
259     }
260
261     public static InetAddress[] getMailExchangerIPs(String hostName) {
262         InetAddress[] ret;
263         try {
264             Hashtable env = new Hashtable();
265             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
266             DirContext ictx = new InitialDirContext(env);
267             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
268             Attribute attr = attrs.get("MX");
269             if (attr == null) {
270                 ret = new InetAddress[1];
271                 try {
272                     ret[0] = InetAddress.getByName(hostName);
273                     return ret;
274                 } catch (UnknownHostException uhe) {
275                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
276                     return new InetAddress[0];
277                 }
278             } else {
279                 ret = new InetAddress[attr.size()];
280                 NamingEnumeration ne = attr.getAll();
281                 for(int i=0; ne.hasMore(); i++) {
282                     String mx = (String)ne.next();
283                     // FIXME we should be sorting here
284                     mx = mx.substring(mx.indexOf(" ") + 1);
285                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
286                     ret[i] = InetAddress.getByName(mx);
287                 }
288             }
289         } catch (Exception e) {
290             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
291             Log.warn(SMTP.class, e);
292             return new InetAddress[0];
293         }
294         return ret;
295     }
296 }