bogus
[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     // Server //////////////////////////////////////////////////////////////////////////////
23
24     public static class Server implements Worker {
25         public void handleRequest(Connection conn) {
26             Log.error(this, "accepted...");
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                 if (command == null) return;
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, Connection conn) {
124             while (s.charAt(3) == '-') s = conn.readln();
125             if (s.startsWith("4")||s.startsWith("5")) throw new MailException(s);
126         }
127         private static boolean attempt(final Message m, final InetAddress mx) {
128             boolean accepted = false;
129             Connection conn = null;
130             try {
131                 Log.info(SMTP.Outgoing.class, "connecting to " + mx + "...");
132                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
133                 conn.setTimeout(60 * 1000);
134                 Log.info(SMTP.Outgoing.class, "connected");
135                 check(conn.readln(), conn);  // banner
136                 conn.println("HELO " + conn.vhost);            check(conn.readln(), conn);
137                 conn.println("MAIL FROM:<" + m.envelopeFrom.user + "@" + m.envelopeFrom.host+">");  check(conn.readln(), conn);
138                 conn.println("RCPT TO:<"   + m.envelopeTo.user + "@" + m.envelopeTo.host+">");      check(conn.readln(), conn);
139                 conn.println("DATA");                          check(conn.readln(), conn);
140                 conn.println(m.toString());
141                 conn.println(".");
142                 check(conn.readln(), conn);
143                 Log.info(SMTP.Outgoing.class, "success: message accepted by " + mx);
144                 accepted = true;
145                 conn.close();
146             } catch (Exception e) {
147                 if (accepted) return true;
148                 Log.warn(SMTP.Outgoing.class, "unable to send; error=" + e);
149                 Log.warn(SMTP.Outgoing.class, e);
150                 return false;
151             } finally {
152                 if (conn != null) conn.close();
153             }
154             return accepted;
155         }
156
157         static void runq() {
158             try {
159                 Log.setThreadAnnotation("[outgoing smtp] ");
160                 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
161                 while(true) {
162                     for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
163                         try                   { if (attempt(it.cur())) it.delete(); }
164                         catch (Exception e)   { Log.error(SMTP.Outgoing.class, e); }
165                     }
166                     synchronized(Outgoing.class) {
167                         Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
168                         Outgoing.class.wait(5 * 60 * 1000);
169                         deadHosts.clear();
170                         Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
171                     }
172                 }
173             } catch (Exception e) { Log.error(SMTP.Outgoing.class, e); }
174         }
175     }
176
177     public static InetAddress[] getMailExchangerIPs(String hostName) {
178         InetAddress[] ret;
179         try {
180             Hashtable env = new Hashtable();
181             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
182             DirContext ictx = new InitialDirContext(env);
183             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
184             Attribute attr = attrs.get("MX");
185             if (attr == null) {
186                 ret = new InetAddress[1];
187                 try {
188                     ret[0] = InetAddress.getByName(hostName);
189                     return ret;
190                 } catch (UnknownHostException uhe) {
191                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
192                     return new InetAddress[0];
193                 }
194             } else {
195                 ret = new InetAddress[attr.size()];
196                 NamingEnumeration ne = attr.getAll();
197                 for(int i=0; ne.hasMore(); i++) {
198                     String mx = (String)ne.next();
199                     // FIXME we should be sorting here
200                     mx = mx.substring(mx.indexOf(" ") + 1);
201                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
202                     ret[i] = InetAddress.getByName(mx);
203                 }
204             }
205         } catch (Exception e) {
206             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
207             Log.warn(SMTP.class, e);
208             return new InetAddress[0];
209         }
210         return ret;
211     }
212 }