more fixups to MailingList
[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.util.*;
9 import org.ibex.io.*;
10 import java.net.*;
11 import java.io.*;
12 import java.util.*;
13 import java.text.*;
14 import javax.naming.*;
15 import javax.naming.directory.*;
16
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
25 public class SMTP {
26
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);
30
31     static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
32
33     public static void accept(Message m) throws IOException {
34         if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
35         else                         Target.root.accept(m);
36     }
37
38     public static class SMTPException extends MailException {
39         int code;
40         String message;
41         public SMTPException(String s) {
42             code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
43             message = s.substring(s.indexOf(' ')+1);
44         }
45         public String toString() { return "SMTP " + code + ": " + message; }
46         public String getMessage() { return toString(); }
47     }
48
49     // Server //////////////////////////////////////////////////////////////////////////////
50
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());
56             Address from = null;
57             Vector to = new Vector();
58             boolean ehlo = false;
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();
69                     conn.println("250");
70                     ehlo = true;     
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);
87                     if (addr.isLocal()) {
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"); }
93                     to.addElement(addr);
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");
98                     conn.flush();
99                     try {
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");
105                         while(true) {
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");
111                         }
112                         String body = buf.toString();
113                         Message m = null;
114                         for(int i=0; i<to.size(); i++) {
115                             m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
116                             accept(m);
117                         }
118                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
119                         conn.println("250 message accepted");
120                         conn.flush();
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);
128                         conn.close();
129                         return;
130                     }
131                 } else                    { conn.println("500 unrecognized command"); }                    
132             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
133         }
134     }
135
136
137     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
138
139     public static class Outgoing {
140
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());
145             /*
146             if (m.traces.length >= 100)
147                 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
148             */
149             else synchronized(Outgoing.class) {
150                 spool.add(m);
151                 Outgoing.class.notify();
152             }
153         }
154
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());
158                 return false;
159             }
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));
164                 return true;
165             }
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"));
169                 return true;
170             }
171             for(int i=0; i<mx.length; i++) {
172                 if (deadHosts.contains(mx[i])) continue;
173                 if (attempt(m, mx[i])) { return true; }
174             }
175             return false;
176         }
177
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);
181         }
182         private static boolean attempt(final Message m, final InetAddress mx) {
183             boolean accepted = false;
184             Connection conn = null;
185             try {
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
192                 try {
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);
198                 }
199                 if (m.envelopeFrom==null) {
200                     conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
201                 } else {
202                     conn.println("MAIL FROM:<" + m.envelopeFrom.user + "@" + m.envelopeFrom.host+">");  check(conn.readln(), conn);
203                 }
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;
208                 while(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(".");
215                     conn.println(s);
216                 }
217                 conn.println(".");
218                 check(conn.readln(), conn);
219                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary());
220                 accepted = true;
221                 conn.close();
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);
227                 return false;
228             } finally {
229                 if (conn != null) conn.close();
230             }
231             return accepted;
232         }
233
234         static void runq() {
235             try {
236                 Log.setThreadAnnotation("[outgoing smtp] ");
237                 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
238                 while(true) {
239                     if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
240                     for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
241                         try {
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);
247                         }
248                     }
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);
253                         deadHosts.clear();
254                         Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
255                     }
256                 }
257             } catch (Exception e) {
258                 Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e);
259                 Log.error(SMTP.Outgoing.class, e);
260             }
261         }
262     }
263
264     public static InetAddress[] getMailExchangerIPs(String hostName) {
265         InetAddress[] ret;
266         try {
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");
272             if (attr == null) {
273                 ret = new InetAddress[1];
274                 try {
275                     ret[0] = InetAddress.getByName(hostName);
276                     return ret;
277                 } catch (UnknownHostException uhe) {
278                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
279                     return new InetAddress[0];
280                 }
281             } else {
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);
290                 }
291             }
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];
296         }
297         return ret;
298     }
299 }