removed Message.Envelope class
[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                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
75                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
76                         buf.append("          for "); for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
77                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
78                         while(true) {
79                             String s = conn.readln();
80                             if (s == null) throw new RuntimeException("connection closed");
81                             if (s.equals(".")) break;
82                             if (s.startsWith(".")) s = s.substring(1);
83                             buf.append(s + "\r\n");
84                         }
85                         String body = buf.toString();
86                         Message m = null;
87                         for(int i=0; i<to.size(); i++) {
88                             m = Message.newMessage(new Stream(body), from, (Address)to.elementAt(i));
89                             if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
90                             else                         Target.root.accept(m);
91                         }
92                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
93                         conn.println("250 message accepted");
94                         conn.flush();
95                         from = null; to = new Vector();
96                     } catch (MailException.Malformed mfe) {   conn.println("501 " + mfe.toString());
97                     } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
98                     } catch (IOException ioe) {               
99                         //conn.println("554 " + ioe.toString());
100                         Log.error(this, ioe);
101                         conn.close();
102                         return;
103                     }
104                 } else                    { conn.println("500 unrecognized command"); }                    
105             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
106         }
107     }
108
109
110     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
111
112     public static class Outgoing {
113
114         private static final HashSet deadHosts = new HashSet();
115         public static void accept(Message m) throws IOException {
116             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
117             //Log.info(SMTP.class, "queued: " + m.summary());
118             if (m.traces.length >= 100)
119                 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
120             else synchronized(Outgoing.class) {
121                 spool.add(m);
122                 Outgoing.class.notify();
123             }
124         }
125
126         public static boolean attempt(Message m) throws IOException {
127             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
128             if (mx.length == 0) {
129                 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
130                 accept(m.bounce("could not resolve " + m.envelopeTo.host));
131                 return true;
132             }
133             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
134                 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
135                 accept(m.bounce("could not send for 5 days"));
136                 return true;
137             }
138             for(int i=0; i<mx.length; i++) {
139                 if (deadHosts.contains(mx[i])) continue;
140                 if (attempt(m, mx[i])) { return true; }
141             }
142             return false;
143         }
144
145         private static void check(String s, Connection conn) {
146             while (s.charAt(3) == '-') s = conn.readln();
147             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
148         }
149         private static boolean attempt(final Message m, final InetAddress mx) {
150             boolean accepted = false;
151             Connection conn = null;
152             try {
153                 Log.note("connecting to " + mx + "...");
154                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
155                 conn.setNewline("\r\n");
156                 conn.setTimeout(60 * 1000);
157                 Log.note("    connected");
158                 check(conn.readln(), conn);  // banner
159                 conn.println("HELO " + conn.vhost);            check(conn.readln(), conn);
160                 conn.println("MAIL FROM:<" + m.envelope.from.user + "@" + m.envelope.from.host+">");  check(conn.readln(), conn);
161                 conn.println("RCPT TO:<"   + m.envelope.to.user + "@" + m.envelope.to.host+">");      check(conn.readln(), conn);
162                 conn.println("DATA");                          check(conn.readln(), conn);
163                 Stream stream = new Stream(m.toString());
164                 boolean inheaders = true;
165                 while(true) {
166                     String s = stream.readln();
167                     if (s == null) break;
168                     if (s.length() == 0) inheaders = false;
169                     // quash Return-Path; required by RFC2822
170                     if (inheaders && s.toLowerCase().startsWith("Return-Path:")) continue;
171                     if (s.startsWith(".")) conn.print(".");
172                     conn.println(s);
173                 }
174                 conn.println(".");
175                 check(conn.readln(), conn);
176                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary());
177                 accepted = true;
178                 conn.close();
179             } catch (Exception e) {
180                 if (accepted) return true;
181                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
182                 Log.warn(SMTP.Outgoing.class, e);
183                 return false;
184             } finally {
185                 if (conn != null) conn.close();
186             }
187             return accepted;
188         }
189
190         static void runq() {
191             try {
192                 Log.setThreadAnnotation("[outgoing smtp] ");
193                 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
194                 while(true) {
195                     if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
196                     for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
197                         try {
198                             if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
199                             if (attempt(it.cur())) it.delete();
200                         } catch (Exception e)   {
201                             if (e instanceof InterruptedException) throw e;
202                             Log.error(SMTP.Outgoing.class, e);
203                         }
204                     }
205                     synchronized(Outgoing.class) {
206                         if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
207                         Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
208                         Outgoing.class.wait(5 * 60 * 1000);
209                         deadHosts.clear();
210                         Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
211                     }
212                 }
213             } catch (Exception e) {
214                 Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e);
215                 Log.error(SMTP.Outgoing.class, e);
216             }
217         }
218     }
219
220     public static InetAddress[] getMailExchangerIPs(String hostName) {
221         InetAddress[] ret;
222         try {
223             Hashtable env = new Hashtable();
224             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
225             DirContext ictx = new InitialDirContext(env);
226             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
227             Attribute attr = attrs.get("MX");
228             if (attr == null) {
229                 ret = new InetAddress[1];
230                 try {
231                     ret[0] = InetAddress.getByName(hostName);
232                     return ret;
233                 } catch (UnknownHostException uhe) {
234                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
235                     return new InetAddress[0];
236                 }
237             } else {
238                 ret = new InetAddress[attr.size()];
239                 NamingEnumeration ne = attr.getAll();
240                 for(int i=0; ne.hasMore(); i++) {
241                     String mx = (String)ne.next();
242                     // FIXME we should be sorting here
243                     mx = mx.substring(mx.indexOf(" ") + 1);
244                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
245                     ret[i] = InetAddress.getByName(mx);
246                 }
247             }
248         } catch (Exception e) {
249             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
250             Log.warn(SMTP.class, e);
251             return new InetAddress[0];
252         }
253         return ret;
254     }
255 }