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