b47585f1f893679196a593a76967eedc11c62620
[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 // FEATURE: exponential backoff on retry time?
15 public class SMTP {
16
17     private static final Mailbox spool =
18         FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
19
20     static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
21
22     public static class SMTPException extends MailException {
23         int code;
24         String message;
25         public SMTPException(String s) {
26             code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
27             message = s.substring(s.indexOf(' ')+1);
28         }
29         public String toString() { return "SMTP " + code + ": " + message; }
30         public String getMessage() { return toString(); }
31     }
32
33     // Server //////////////////////////////////////////////////////////////////////////////
34
35     public static class Server implements Worker {
36         public void handleRequest(Connection conn) {
37             conn.setTimeout(5 * 60 * 1000);
38             conn.setNewline("\r\n");
39             conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
40             Address from = null;
41             Vector to = new Vector();
42             for(String command = conn.readln(); ; command = conn.readln()) try {
43                 if (command == null) return;
44                 String c = command.toUpperCase();
45                 if (c.startsWith("HELO"))        { conn.println("250 HELO " + conn.vhost); from = null; to = new Vector();
46                 } else if (c.startsWith("EHLO")) { conn.println("250");                    from = null; to = new Vector();
47                 } else if (c.startsWith("RSET")) { conn.println("250 reset ok");           from = null; to = new Vector();
48                 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help.  see a trained professional.");
49                 } else if (c.startsWith("VRFY")) { conn.println("252 We don't VRFY; proceed anyway");
50                 } else if (c.startsWith("EXPN")) { conn.println("550 EXPN not available");
51                 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
52                 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
53                 } else if (c.startsWith("MAIL FROM:")) {
54                     command = command.substring(10).trim();
55                     from = command.equals("<>") ? null : new Address(command);
56                     conn.println("250 " + from + " is syntactically correct");
57                 } else if (c.startsWith("RCPT TO:")) {
58                     //if (from == null) { conn.println("503 MAIL FROM must precede RCPT TO"); continue; }
59                     command = command.substring(8).trim();
60                     if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
61                     Address addr = new Address(command);
62                     if (addr.isLocal()) conn.println("250 " + addr + " is on this machine; I will deliver it");
63                     else if (conn.getRemoteAddress().isLoopbackAddress())
64                         conn.println("250 you are connected locally, so I will let you send");
65                     else { conn.println("551 sorry, " + addr + " is not on this machine"); }
66                     to.addElement(addr);
67                 } else if (c.startsWith("DATA")) {
68                     if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
69                     if (to == null) { conn.println("503 RCPT TO command must precede DATA"); continue; }
70                     conn.println("354 Enter message, ending with \".\" on a line by itself");
71                     conn.flush();
72                     try {
73                         StringBuffer buf = new StringBuffer();
74                         while(true) {
75                             String s = conn.readln();
76                             if (s == null) throw new RuntimeException("connection closed");
77                             if (s.equals(".")) break;
78                             if (s.startsWith(".")) s = s.substring(1);
79                             buf.append(s + "\r\n");
80                         }
81                         String body = buf.toString();
82                         Message m = null;
83                         for(int i=0; i<to.size(); i++) {
84                             m = Message.newMessage(new Stream(body), from, (Address)to.elementAt(i));
85                             if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
86                             else                         Target.root.accept(m);
87                         }
88                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
89                         conn.println("250 message accepted");
90                         conn.flush();
91                         from = null; to = new Vector();
92                     } catch (MailException.Malformed mfe) {   conn.println("501 " + mfe.toString());
93                     } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
94                     } catch (IOException ioe) {               
95                         //conn.println("554 " + ioe.toString());
96                         Log.error(this, ioe);
97                         conn.close();
98                         return;
99                     }
100                 } else                    { conn.println("500 unrecognized command"); }                    
101             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
102         }
103     }
104
105
106     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
107
108     public static class Outgoing {
109
110         private static final HashSet deadHosts = new HashSet();
111         public static void accept(Message m) throws IOException {
112             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
113             //Log.info(SMTP.class, "queued: " + m.summary());
114             if (m.traces.length >= 100)
115                 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
116             else synchronized(Outgoing.class) {
117                 spool.add(m);
118                 Outgoing.class.notify();
119             }
120         }
121
122         public static boolean attempt(Message m) throws IOException {
123             InetAddress[] mx = getMailExchangerIPs(m.envelope.to.host);
124             if (mx.length == 0) {
125                 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
126                 accept(m.bounce("could not resolve " + m.envelopeTo.host));
127                 return true;
128             }
129             if (new Date().getTime() - m.envelope.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
130                 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
131                 accept(m.bounce("could not send for 5 days"));
132                 return true;
133             }
134             for(int i=0; i<mx.length; i++) {
135                 if (deadHosts.contains(mx[i])) continue;
136                 if (attempt(m, mx[i])) { return true; }
137             }
138             return false;
139         }
140
141         private static void check(String s, Connection conn) {
142             while (s.charAt(3) == '-') s = conn.readln();
143             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
144         }
145         private static boolean attempt(final Message m, final InetAddress mx) {
146             boolean accepted = false;
147             Connection conn = null;
148             try {
149                 Log.note("connecting to " + mx + "...");
150                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
151                 conn.setNewline("\r\n");
152                 conn.setTimeout(60 * 1000);
153                 Log.note("    connected");
154                 check(conn.readln(), conn);  // banner
155                 conn.println("HELO " + conn.vhost);            check(conn.readln(), conn);
156                 conn.println("MAIL FROM:<" + m.envelope.from.user + "@" + m.envelope.from.host+">");  check(conn.readln(), conn);
157                 conn.println("RCPT TO:<"   + m.envelope.to.user + "@" + m.envelope.to.host+">");      check(conn.readln(), conn);
158                 conn.println("DATA");                          check(conn.readln(), conn);
159                 conn.println(m.toString());
160                 conn.println(".");
161                 check(conn.readln(), conn);
162                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary());
163                 accepted = true;
164                 conn.close();
165             } catch (Exception e) {
166                 if (accepted) return true;
167                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
168                 Log.warn(SMTP.Outgoing.class, e);
169                 return false;
170             } finally {
171                 if (conn != null) conn.close();
172             }
173             return accepted;
174         }
175
176         static void runq() {
177             try {
178                 Log.setThreadAnnotation("[outgoing smtp] ");
179                 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
180                 while(true) {
181                     if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
182                     for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
183                         try {
184                             if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
185                             if (attempt(it.cur())) it.delete();
186                         } catch (Exception e)   {
187                             if (e instanceof InterruptedException) throw e;
188                             Log.error(SMTP.Outgoing.class, e);
189                         }
190                     }
191                     synchronized(Outgoing.class) {
192                         if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
193                         Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
194                         Outgoing.class.wait(5 * 60 * 1000);
195                         deadHosts.clear();
196                         Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
197                     }
198                 }
199             } catch (Exception e) {
200                 Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e);
201                 Log.error(SMTP.Outgoing.class, e);
202             }
203         }
204     }
205
206     public static InetAddress[] getMailExchangerIPs(String hostName) {
207         InetAddress[] ret;
208         try {
209             Hashtable env = new Hashtable();
210             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
211             DirContext ictx = new InitialDirContext(env);
212             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
213             Attribute attr = attrs.get("MX");
214             if (attr == null) {
215                 ret = new InetAddress[1];
216                 try {
217                     ret[0] = InetAddress.getByName(hostName);
218                     return ret;
219                 } catch (UnknownHostException uhe) {
220                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
221                     return new InetAddress[0];
222                 }
223             } else {
224                 ret = new InetAddress[attr.size()];
225                 NamingEnumeration ne = attr.getAll();
226                 for(int i=0; ne.hasMore(); i++) {
227                     String mx = (String)ne.next();
228                     // FIXME we should be sorting here
229                     mx = mx.substring(mx.indexOf(" ") + 1);
230                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
231                     ret[i] = InetAddress.getByName(mx);
232                 }
233             }
234         } catch (Exception e) {
235             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
236             Log.warn(SMTP.class, e);
237             return new InetAddress[0];
238         }
239         return ret;
240     }
241 }