mailing list improvements (and nntp)
[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.net.*;
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: logging: current logging sucks
19 // FIXME: loop prevention
20 // FIXME: probably need some throttling on outbound mail
21
22 // graylisting?
23
24 // FEATURE: infer messageid, date, if not present (?)
25 // FEATURE: exponential backoff on retry time?
26 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
27 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
28 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
29 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
30 public class SMTP {
31
32     public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
33     public static final int numOutgoingThreads = 5;
34     private static final Mailbox spool =
35         FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
36
37     static {
38         for(int i=0; i<numOutgoingThreads; i++)
39             new Outgoing().start();
40     }
41
42     public static void accept(Message m) throws IOException {
43         if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
44         else                         Target.root.accept(m);
45     }
46
47     public static class SMTPException extends MailException {
48         int code;
49         String message;
50         public SMTPException(String s) {
51             try {
52                 code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
53                 message = s.substring(s.indexOf(' ')+1);
54             } catch (NumberFormatException nfe) {
55                 code = -1;
56                 message = s;
57             }
58         }
59         public String toString() { return "SMTP " + code + ": " + message; }
60         public String getMessage() { return toString(); }
61     }
62
63     // Server //////////////////////////////////////////////////////////////////////////////
64
65     public static class Server {
66         public void handleRequest(Connection conn) {
67             conn.setTimeout(5 * 60 * 1000);
68             conn.setNewline("\r\n");
69             conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
70             Address from = null;
71             Vector to = new Vector();
72             boolean ehlo = false;
73             String remotehost = null;
74             for(String command = conn.readln(); ; command = conn.readln()) try {
75                 if (command == null) return;
76                 Log.warn("**"+conn.getRemoteAddress()+"**", command);
77                 String c = command.toUpperCase();
78                 if (c.startsWith("HELO"))        {
79                     remotehost = c.substring(5).trim();
80                     conn.println("250 HELO " + conn.vhost);
81                     from = null; to = new Vector();
82                 } else if (c.startsWith("EHLO")) {
83                     remotehost = c.substring(5).trim();
84                     conn.println("250 "+conn.vhost+" greets " + remotehost);
85                     ehlo = true;     
86                     from = null; to = new Vector();
87                 } else if (c.startsWith("RSET")) { conn.println("250 reset ok");           from = null; to = new Vector();
88                 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help.  see a trained professional.");
89                 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
90                 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
91                 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
92                 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
93                 } else if (c.startsWith("MAIL FROM:")) {
94                     command = command.substring(10).trim();
95                     from = command.equals("<>") ? null : new Address(command);
96                     conn.println("250 " + from + " is syntactically correct");
97                 } else if (c.startsWith("RCPT TO:")) {
98                     // some clients are broken and put RCPT first; we will tolerate this
99                     command = command.substring(8).trim();
100                     if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
101                     Address addr = new Address(command);
102                     /*
103                     Log.warn("**"+conn.getRemoteAddress()+"**",
104                              "addr.isLocal(): " + addr.isLocal() + "\n" +
105                              "conn.getRemoteAddress().isLoopbackAddress(): " + conn.getRemoteAddress().isLoopbackAddress() + "\n" +
106                              "johnw: " + (from!=null&&from.toString().indexOf("johnw")!=-1) + "\n"
107                              );
108                     */
109                     if (addr.isLocal()) {
110                         // FEATURE: should check the address further and give 550 if undeliverable
111                         conn.println("250 " + addr + " is on this machine; I will deliver it");
112                         to.addElement(addr);
113                     } else if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
114                         conn.println("250 you are connected locally, so I will let you send");
115                         to.addElement(addr);
116                     } else {
117                         conn.println("551 sorry, " + addr + " is not on this machine");
118                     }
119                 } else if (c.startsWith("DATA")) {
120                     //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
121                     if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
122                     conn.println("354 Enter message, ending with \".\" on a line by itself");
123                     conn.flush();
124                     try {
125                         StringBuffer buf = new StringBuffer();
126                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
127                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
128                         buf.append("          for ");
129                         // FIXME: this is leaking BCC addrs
130                         // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
131                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
132                         while(true) {
133                             String s = conn.readln();
134                             if (s == null) throw new RuntimeException("connection closed");
135                             if (s.equals(".")) break;
136                             if (s.startsWith(".")) s = s.substring(1);
137                             buf.append(s + "\r\n");
138                         }
139                         String body = buf.toString();
140                         Message m = null;
141                         for(int i=0; i<to.size(); i++) {
142                             m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
143                             accept(m);
144                         }
145                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
146                         conn.println("250 message accepted");
147                         conn.flush();
148                         from = null; to = new Vector();
149                     } catch (Reject.RejectException re) {
150                         Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n   " + re.m.summary());
151                         conn.println("501 " + re.reason);
152                     } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
153                     } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
154                     } catch (Later.LaterException le) {       conn.println("453 try again later");
155                     } catch (IOException ioe) {               
156                         //conn.println("554 " + ioe.toString());
157                         Log.error(this, ioe);
158                         conn.close();
159                         return;
160                     }
161                 } else                    { conn.println("500 unrecognized command"); }                    
162             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
163         }
164     }
165
166
167     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
168
169     public static class Outgoing extends Thread {
170
171         private static final HashSet deadHosts = new HashSet();
172         public static void accept(Message m) throws IOException {
173             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
174             String traces = m.headers.get("Received");
175             if (traces!=null) {
176                 int lines = 0;
177                 for(int i=0; i<traces.length(); i++)
178                     if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
179                         lines++;
180                 if (lines > 100) { // required by rfc
181                     Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
182                     return;
183                 }
184             }
185             synchronized(Outgoing.class) {
186                 spool.add(m);
187                 Outgoing.class.notifyAll();
188             }
189         }
190
191         public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
192         public static boolean attempt(Message m, boolean noBounces) throws IOException {
193             if (m.envelopeTo == null) {
194                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
195                 return false;
196             }
197             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
198             if (mx.length == 0) {
199                 if (!noBounces) {
200                     accept(m.bounce("could not resolve " + m.envelopeTo.host));
201                     return true;
202                 } else {
203                     Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
204                     return false;
205                 }
206             }
207             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
208                 if (!noBounces) {
209                     accept(m.bounce("could not send for 5 days"));
210                     return true;
211                 } else {
212                     Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
213                     return false;
214                 }
215             }
216             for(int i=0; i<mx.length; i++) {
217                 //if (deadHosts.contains(mx[i])) continue;
218                 if (attempt(m, mx[i])) { return true; }
219             }
220             return false;
221         }
222
223         private static void check(String s, Connection conn) {
224             if (s==null) return;
225             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
226             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
227         }
228         private static boolean attempt(final Message m, final InetAddress mx) {
229             boolean accepted = false;
230             Connection conn = null;
231             try {
232                 Log.note("connecting to " + mx + "...");
233                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
234                 conn.setNewline("\r\n");
235                 conn.setTimeout(60 * 1000);
236                 Log.note("    connected");
237                 check(conn.readln(), conn);  // banner
238                 try {
239                     conn.println("EHLO " + conn.vhost);
240                     check(conn.readln(), conn);
241                 } catch (SMTPException smtpe) {
242                     conn.println("HELO " + conn.vhost);
243                     check(conn.readln(), conn);
244                 }
245                 if (m.envelopeFrom==null) {
246                     Log.warn("", "MAIL FROM:<>");
247                     conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
248                 } else {
249                     Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
250                     conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">");  check(conn.readln(), conn);
251                 }
252                 conn.println("RCPT TO:<"   + m.envelopeTo.toString()+">");      check(conn.readln(), conn);
253                 conn.println("DATA");                          check(conn.readln(), conn);
254                 Headers head = m.headers;
255                 head = head.remove("return-path");
256                 head = head.remove("bcc");
257                 Stream stream = head.getStream();
258                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
259                     if (s.startsWith(".")) conn.print(".");
260                     conn.println(s);
261                 }
262                 conn.println("");
263                 stream = m.getBody().getStream();
264                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
265                     if (s.startsWith(".")) conn.print(".");
266                     conn.println(s);
267                 }
268                 conn.println(".");
269                 String resp = conn.readln();
270                 if (resp == null)
271                     throw new SMTPException("server " + mx + " closed connection without accepting message");
272                 check(resp, conn);
273                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
274                 accepted = true;
275                 conn.close();
276             } catch (SMTPException e) {
277                 if (accepted) return true;
278                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
279                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
280                 Log.warn(SMTP.Outgoing.class, e);
281                 if (e.code >= 500 && e.code <= 599) {
282                     try {
283                         attempt(m.bounce("unable to deliver: " + e), true);
284                     } catch (Exception ex) {
285                         Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
286                         Log.error(SMTP.Outgoing.class, ex);
287                     }
288                     return true;
289                 }
290                 return false;
291             } catch (Exception e) {
292                 if (accepted) return true;
293                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
294                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
295                 Log.warn(SMTP.Outgoing.class, e);
296                 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
297                 return false;
298             } finally {
299                 if (conn != null) conn.close();
300             }
301             return accepted;
302         }
303
304         private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
305         private static int serials = 1;
306         private int serial = serials++;
307         private Mailbox.Iterator it;
308
309         public Outgoing() {
310             synchronized(Outgoing.class) {
311                 threads.add(this);
312             }
313         }
314
315         public void wake() {
316             int count = spool.count(Query.all());
317             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
318             try {
319                 while(true) {
320                     boolean good = false;
321                     synchronized(Outgoing.class) {
322                         it = spool.iterator();
323                         OUTER: for(; it.next(); ) {
324                             for(Outgoing o : threads)
325                                 if (o!=this && o.it != null && o.it.uid()==it.uid())
326                                     continue OUTER;
327                             good = true;
328                             break;
329                         }
330                     }
331                     if (!good) break;
332                     try {
333                         if (attempt(it.cur())) it.delete();
334                     } catch (Exception e) {
335                         Log.error(SMTP.Outgoing.class, e);
336                     }
337                     Log.info(this, "sleeping for 3s...");
338                     Thread.sleep(3000);
339                 }
340             } catch (Exception e) {
341                 //if (e instanceof InterruptedException) throw e;
342                 Log.error(SMTP.Outgoing.class, e);
343             }
344             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
345             it = null;
346         }
347
348         public void run() {
349             try {
350                 while(true) {
351                     Log.setThreadAnnotation("[outgoing #"+serial+"] ");
352                     wake();
353                     Thread.sleep(1000);
354                     synchronized(Outgoing.class) {
355                         Outgoing.class.wait(5 * 60 * 1000);
356                     }
357                 }
358             } catch (InterruptedException e) { Log.warn(this, e); }
359         }
360     }
361
362     public static InetAddress[] getMailExchangerIPs(String hostName) {
363         InetAddress[] ret;
364         try {
365             Hashtable env = new Hashtable();
366             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
367             DirContext ictx = new InitialDirContext(env);
368             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
369             Attribute attr = attrs.get("MX");
370             if (attr == null) {
371                 ret = new InetAddress[1];
372                 try {
373                     ret[0] = InetAddress.getByName(hostName);
374                     if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException();
375                     return ret;
376                 } catch (UnknownHostException uhe) {
377                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
378                     return new InetAddress[0];
379                 }
380             } else {
381                 ret = new InetAddress[attr.size()];
382                 NamingEnumeration ne = attr.getAll();
383                 for(int i=0; ne.hasMore();) {
384                     String mx = (String)ne.next();
385                     // FIXME we should be sorting here
386                     mx = mx.substring(mx.indexOf(" ") + 1);
387                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
388                     InetAddress ia = InetAddress.getByName(mx);
389                     if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue;
390                     ret[i++] = ia;
391                 }
392             }
393         } catch (Exception e) {
394             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
395             Log.warn(SMTP.class, e);
396             return new InetAddress[0];
397         }
398         return ret;
399     }
400 }