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