8d16b43544b9821c212fa8f1dbf623fc101e9876
[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                     if (addr.isLocal()) {
103                         // FEATURE: should check the address further and give 550 if undeliverable
104                         conn.println("250 " + addr + " is on this machine; I will deliver it");
105                         to.addElement(addr);
106                     } else if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) {
107                         conn.println("250 you are connected locally, so I will let you send");
108                         to.addElement(addr);
109                     } else {
110                         conn.println("551 sorry, " + addr + " is not on this machine");
111                     }
112                 } else if (c.startsWith("DATA")) {
113                     //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
114                     if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; }
115                     conn.println("354 Enter message, ending with \".\" on a line by itself");
116                     conn.flush();
117                     try {
118                         StringBuffer buf = new StringBuffer();
119                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
120                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
121                         buf.append("          for ");
122                         // FIXME: this is leaking BCC addrs
123                         // for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
124                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
125                         while(true) {
126                             String s = conn.readln();
127                             if (s == null) throw new RuntimeException("connection closed");
128                             if (s.equals(".")) break;
129                             if (s.startsWith(".")) s = s.substring(1);
130                             buf.append(s + "\r\n");
131                         }
132                         String body = buf.toString();
133                         Message m = null;
134                         for(int i=0; i<to.size(); i++) {
135                             m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
136                             accept(m);
137                         }
138                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
139                         conn.println("250 message accepted");
140                         conn.flush();
141                         from = null; to = new Vector();
142                     } catch (Reject.RejectException re) {
143                         Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n   " + re.m.summary());
144                         conn.println("501 " + re.reason);
145                     } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString());
146                     } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
147                     } catch (Later.LaterException le) {       conn.println("453 try again later");
148                     } catch (IOException ioe) {               
149                         //conn.println("554 " + ioe.toString());
150                         Log.error(this, ioe);
151                         conn.close();
152                         return;
153                     }
154                 } else                    { conn.println("500 unrecognized command"); }                    
155             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
156         }
157     }
158
159
160     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
161
162     public static class Outgoing extends Thread {
163
164         private static final HashSet deadHosts = new HashSet();
165         public static void accept(Message m) throws IOException {
166             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
167             String traces = m.headers.get("Received");
168             if (traces!=null) {
169                 int lines = 0;
170                 for(int i=0; i<traces.length(); i++)
171                     if (traces.charAt(i)=='\n' || traces.charAt(i)=='\r')
172                         lines++;
173                 if (lines > 100) { // required by rfc
174                     Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary());
175                     return;
176                 }
177             }
178             synchronized(Outgoing.class) {
179                 spool.add(m);
180                 Outgoing.class.notifyAll();
181             }
182         }
183
184         public static boolean attempt(Message m) throws IOException { return attempt(m, false); }
185         public static boolean attempt(Message m, boolean noBounces) throws IOException {
186             if (m.envelopeTo == null) {
187                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
188                 return false;
189             }
190             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
191             if (mx.length == 0) {
192                 if (!noBounces) {
193                     accept(m.bounce("could not resolve " + m.envelopeTo.host));
194                     return true;
195                 } else {
196                     Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host);
197                     return false;
198                 }
199             }
200             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
201                 if (!noBounces) {
202                     accept(m.bounce("could not send for 5 days"));
203                     return true;
204                 } else {
205                     Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary());
206                     return false;
207                 }
208             }
209             for(int i=0; i<mx.length; i++) {
210                 //if (deadHosts.contains(mx[i])) continue;
211                 if (attempt(m, mx[i])) { return true; }
212             }
213             return false;
214         }
215
216         private static void check(String s, Connection conn) {
217             if (s==null) return;
218             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
219             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
220         }
221         private static boolean attempt(final Message m, final InetAddress mx) {
222             boolean accepted = false;
223             Connection conn = null;
224             try {
225                 Log.note("connecting to " + mx + "...");
226                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
227                 conn.setNewline("\r\n");
228                 conn.setTimeout(60 * 1000);
229                 Log.note("    connected");
230                 check(conn.readln(), conn);  // banner
231                 try {
232                     conn.println("EHLO " + conn.vhost);
233                     check(conn.readln(), conn);
234                 } catch (SMTPException smtpe) {
235                     conn.println("HELO " + conn.vhost);
236                     check(conn.readln(), conn);
237                 }
238                 if (m.envelopeFrom==null) {
239                     Log.warn("", "MAIL FROM:<>");
240                     conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
241                 } else {
242                     Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">");
243                     conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">");  check(conn.readln(), conn);
244                 }
245                 conn.println("RCPT TO:<"   + m.envelopeTo.toString()+">");      check(conn.readln(), conn);
246                 conn.println("DATA");                          check(conn.readln(), conn);
247                 Headers head = m.headers;
248                 head = head.remove("return-path");
249                 head = head.remove("bcc");
250                 Stream stream = head.getStream();
251                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
252                     if (s.startsWith(".")) conn.print(".");
253                     conn.println(s);
254                 }
255                 conn.println("");
256                 stream = m.getBody().getStream();
257                 for(String s = stream.readln(); s!=null; s=stream.readln()) {
258                     if (s.startsWith(".")) conn.print(".");
259                     conn.println(s);
260                 }
261                 conn.println(".");
262                 String resp = conn.readln();
263                 if (resp == null)
264                     throw new SMTPException("server " + mx + " closed connection without accepting message");
265                 check(resp, conn);
266                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]");
267                 accepted = true;
268                 conn.close();
269             } catch (SMTPException e) {
270                 if (accepted) return true;
271                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
272                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
273                 Log.warn(SMTP.Outgoing.class, e);
274                 if (e.code >= 500 && e.code <= 599) {
275                     try {
276                         attempt(m.bounce("unable to deliver: " + e), true);
277                     } catch (Exception ex) {
278                         Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely");
279                         Log.error(SMTP.Outgoing.class, ex);
280                     }
281                     return true;
282                 }
283                 return false;
284             } catch (Exception e) {
285                 if (accepted) return true;
286                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
287                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
288                 Log.warn(SMTP.Outgoing.class, e);
289                 if (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog());
290                 return false;
291             } finally {
292                 if (conn != null) conn.close();
293             }
294             return accepted;
295         }
296
297         private static HashSet<Outgoing> threads = new HashSet<Outgoing>();
298         private static int serials = 1;
299         private int serial = serials++;
300         private Mailbox.Iterator it;
301
302         public Outgoing() {
303             synchronized(Outgoing.class) {
304                 threads.add(this);
305             }
306         }
307
308         public void wake() {
309             int count = spool.count(Query.all());
310             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send");
311             try {
312                 while(true) {
313                     boolean good = false;
314                     synchronized(Outgoing.class) {
315                         it = spool.iterator();
316                         OUTER: for(; it.next(); ) {
317                             for(Outgoing o : threads)
318                                 if (o!=this && o.it != null && o.it.uid()==it.uid())
319                                     continue OUTER;
320                             good = true;
321                             break;
322                         }
323                     }
324                     if (!good) break;
325                     try {
326                         if (attempt(it.cur())) it.delete();
327                     } catch (Exception e) {
328                         Log.error(SMTP.Outgoing.class, e);
329                     }
330                     Log.info(this, "sleeping for 3s...");
331                     Thread.sleep(3000);
332                 }
333             } catch (Exception e) {
334                 //if (e instanceof InterruptedException) throw e;
335                 Log.error(SMTP.Outgoing.class, e);
336             }
337             Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep");
338             it = null;
339         }
340
341         public void run() {
342             try {
343                 while(true) {
344                     Log.setThreadAnnotation("[outgoing #"+serial+"] ");
345                     wake();
346                     Thread.sleep(1000);
347                     synchronized(Outgoing.class) {
348                         Outgoing.class.wait(5 * 60 * 1000);
349                     }
350                 }
351             } catch (InterruptedException e) { Log.warn(this, e); }
352         }
353     }
354
355     public static InetAddress[] getMailExchangerIPs(String hostName) {
356         InetAddress[] ret;
357         try {
358             Hashtable env = new Hashtable();
359             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
360             DirContext ictx = new InitialDirContext(env);
361             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
362             Attribute attr = attrs.get("MX");
363             if (attr == null) {
364                 ret = new InetAddress[1];
365                 try {
366                     ret[0] = InetAddress.getByName(hostName);
367                     return ret;
368                 } catch (UnknownHostException uhe) {
369                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
370                     return new InetAddress[0];
371                 }
372             } else {
373                 ret = new InetAddress[attr.size()];
374                 NamingEnumeration ne = attr.getAll();
375                 for(int i=0; ne.hasMore();) {
376                     String mx = (String)ne.next();
377                     // FIXME we should be sorting here
378                     mx = mx.substring(mx.indexOf(" ") + 1);
379                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
380                     InetAddress ia = InetAddress.getByName(mx);
381                     if (ia.equals(IP.getIP(127,0,0,1))) continue;
382                     ret[i++] = ia;
383                 }
384             }
385         } catch (Exception e) {
386             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
387             Log.warn(SMTP.class, e);
388             return new InetAddress[0];
389         }
390         return ret;
391     }
392 }