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