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