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