adjusted for changes to jinetd
[org.ibex.mail.git] / src / org / ibex / mail / protocol / SMTP.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.mail.protocol;
6 import org.ibex.mail.*;
7 import org.ibex.mail.target.*;
8 import org.ibex.util.*;
9 import org.ibex.io.*;
10 import java.net.*;
11 import java.io.*;
12 import java.util.*;
13 import java.text.*;
14 import javax.naming.*;
15 import javax.naming.directory.*;
16
17 // FIXME: bounce messages (must go to return-path unless empty, in which case do not send
18 // FIXME: if more than 100 "Received" lines, must drop message
19 // FEATURE: infer messageid, date, if not present (?)
20 // FEATURE: RFC2822, section 4.5.1: special "postmaster" address
21 // FEATURE: RFC2822, section 4.5.4.1: retry strategies
22 // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering
23 // FEATURE: exponential backoff on retry time?
24 // FEATURE: RFC2822, end of 4.1.2: backslashes in headers
25 public class SMTP {
26
27     public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
28     private static final Mailbox spool =
29         FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true);
30
31     static { new Thread() { public void run() { Outgoing.runq(); } }.start(); }
32
33     public static class SMTPException extends MailException {
34         int code;
35         String message;
36         public SMTPException(String s) {
37             code = Integer.parseInt(s.substring(0, s.indexOf(' ')));
38             message = s.substring(s.indexOf(' ')+1);
39         }
40         public String toString() { return "SMTP " + code + ": " + message; }
41         public String getMessage() { return toString(); }
42     }
43
44     // Server //////////////////////////////////////////////////////////////////////////////
45
46     public static class Server {
47         public void handleRequest(Connection conn) {
48             conn.setTimeout(5 * 60 * 1000);
49             conn.setNewline("\r\n");
50             conn.println("220 " + conn.vhost + " SMTP " + this.getClass().getName());
51             Address from = null;
52             Vector to = new Vector();
53             boolean ehlo = false;
54             String remotehost = null;
55             for(String command = conn.readln(); ; command = conn.readln()) try {
56                 if (command == null) return;
57                 String c = command.toUpperCase();
58                 if (c.startsWith("HELO"))        {
59                     remotehost = c.substring(5).trim();
60                     conn.println("250 HELO " + conn.vhost);
61                     from = null; to = new Vector();
62                 } else if (c.startsWith("EHLO")) {
63                     remotehost = c.substring(5).trim();
64                     conn.println("250");
65                     ehlo = true;     
66                     from = null; to = new Vector();
67                 } else if (c.startsWith("RSET")) { conn.println("250 reset ok");           from = null; to = new Vector();
68                 } else if (c.startsWith("HELP")) { conn.println("214 you are beyond help.  see a trained professional.");
69                 } else if (c.startsWith("VRFY")) { conn.println("502 VRFY not supported");
70                 } else if (c.startsWith("EXPN")) { conn.println("502 EXPN not supported");
71                 } else if (c.startsWith("NOOP")) { conn.println("250 OK");
72                 } else if (c.startsWith("QUIT")) { conn.println("221 " + conn.vhost + " closing connection"); return;
73                 } else if (c.startsWith("MAIL FROM:")) {
74                     command = command.substring(10).trim();
75                     from = command.equals("<>") ? null : new Address(command);
76                     conn.println("250 " + from + " is syntactically correct");
77                 } else if (c.startsWith("RCPT TO:")) {
78                     // some clients are broken and put RCPT first; we will tolerate this
79                     command = command.substring(8).trim();
80                     if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' '));
81                     Address addr = new Address(command);
82                     if (addr.isLocal()) {
83                         // FEATURE: should check the address further and give 550 if undeliverable
84                         conn.println("250 " + addr + " is on this machine; I will deliver it");
85                     } else if (conn.getRemoteAddress().isLoopbackAddress())
86                         conn.println("250 you are connected locally, so I will let you send");
87                     else { conn.println("551 sorry, " + addr + " is not on this machine"); }
88                     to.addElement(addr);
89                 } else if (c.startsWith("DATA")) {
90                     //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; }
91                     if (to == null) { conn.println("503 RCPT TO command must precede DATA"); continue; }
92                     conn.println("354 Enter message, ending with \".\" on a line by itself");
93                     conn.flush();
94                     try {
95                         StringBuffer buf = new StringBuffer();
96                         buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n");
97                         buf.append("          by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n");
98                         buf.append("          for "); for(int i=0; i<to.size(); i++) buf.append(to.elementAt(i) + " ");
99                         buf.append("; " + dateFormat.format(new Date()) + "\r\n");
100                         while(true) {
101                             String s = conn.readln();
102                             if (s == null) throw new RuntimeException("connection closed");
103                             if (s.equals(".")) break;
104                             if (s.startsWith(".")) s = s.substring(1);
105                             buf.append(s + "\r\n");
106                         }
107                         String body = buf.toString();
108                         Message m = null;
109                         for(int i=0; i<to.size(); i++) {
110                             m = Message.newMessage(new Fountain.StringFountain(body), from, (Address)to.elementAt(i));
111                             if (!m.envelopeTo.isLocal()) Outgoing.accept(m);
112                             else                         Target.root.accept(m);
113                         }
114                         if (m != null) Log.info(SMTP.class, "accepted message: " + m.summary());
115                         conn.println("250 message accepted");
116                         conn.flush();
117                         from = null; to = new Vector();
118                     } catch (MailException.Malformed mfe) {   conn.println("501 " + mfe.toString());
119                     } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf);
120                     } catch (Later.LaterException le) {       conn.println("453 try again later");
121                     } catch (IOException ioe) {               
122                         //conn.println("554 " + ioe.toString());
123                         Log.error(this, ioe);
124                         conn.close();
125                         return;
126                     }
127                 } else                    { conn.println("500 unrecognized command"); }                    
128             } catch (Message.Malformed e) { conn.println("501 " + e.toString()); }
129         }
130     }
131
132
133     // Outgoing Mail Thread //////////////////////////////////////////////////////////////////////////////
134
135     public static class Outgoing {
136
137         private static final HashSet deadHosts = new HashSet();
138         public static void accept(Message m) throws IOException {
139             if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; }
140             //Log.info(SMTP.class, "queued: " + m.summary());
141             /*
142             if (m.traces.length >= 100)
143                 Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary());
144             */
145             else synchronized(Outgoing.class) {
146                 spool.add(m);
147                 Outgoing.class.notify();
148             }
149         }
150
151         public static boolean attempt(Message m) throws IOException {
152             if (m.envelopeTo == null) {
153                 Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary());
154                 return false;
155             }
156             InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host);
157             if (mx.length == 0) {
158                 Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary());
159                 accept(m.bounce("could not resolve " + m.envelopeTo.host));
160                 return true;
161             }
162             if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) {
163                 Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary());
164                 accept(m.bounce("could not send for 5 days"));
165                 return true;
166             }
167             for(int i=0; i<mx.length; i++) {
168                 if (deadHosts.contains(mx[i])) continue;
169                 if (attempt(m, mx[i])) { return true; }
170             }
171             return false;
172         }
173
174         private static void check(String s, Connection conn) {
175             while (s.length() > 3 && s.charAt(3) == '-') s = conn.readln();
176             if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s);
177         }
178         private static boolean attempt(final Message m, final InetAddress mx) {
179             boolean accepted = false;
180             Connection conn = null;
181             try {
182                 Log.note("connecting to " + mx + "...");
183                 conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName());
184                 conn.setNewline("\r\n");
185                 conn.setTimeout(60 * 1000);
186                 Log.note("    connected");
187                 check(conn.readln(), conn);  // banner
188                 try {
189                     conn.println("EHLO " + conn.vhost);
190                     check(conn.readln(), conn);
191                 } catch (SMTPException smtpe) {
192                     conn.println("HELO " + conn.vhost);
193                     check(conn.readln(), conn);
194                 }
195                 if (m.envelopeFrom==null) {
196                     conn.println("MAIL FROM:<>");  check(conn.readln(), conn);
197                 } else {
198                     conn.println("MAIL FROM:<" + m.envelopeFrom.user + "@" + m.envelopeFrom.host+">");  check(conn.readln(), conn);
199                 }
200                 conn.println("RCPT TO:<"   + m.envelopeTo.user + "@" + m.envelopeTo.host+">");      check(conn.readln(), conn);
201                 conn.println("DATA");                          check(conn.readln(), conn);
202                 Stream stream = m.getStream();
203                 boolean inheaders = true;
204                 while(true) {
205                     String s = stream.readln();
206                     if (s == null) break;
207                     if (s.length() == 0) inheaders = false;
208                     // quash Return-Path; required by RFC2822
209                     if (inheaders && s.toLowerCase().startsWith("Return-Path:")) continue;
210                     if (s.startsWith(".")) conn.print(".");
211                     conn.println(s);
212                 }
213                 conn.println(".");
214                 check(conn.readln(), conn);
215                 Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary());
216                 accepted = true;
217                 conn.close();
218             } catch (Exception e) {
219                 if (accepted) return true;
220                 Log.warn(SMTP.Outgoing.class, "    unable to send; error=" + e);
221                 Log.warn(SMTP.Outgoing.class, "      message: " + m.summary());
222                 Log.warn(SMTP.Outgoing.class, e);
223                 return false;
224             } finally {
225                 if (conn != null) conn.close();
226             }
227             return accepted;
228         }
229
230         static void runq() {
231             try {
232                 Log.setThreadAnnotation("[outgoing smtp] ");
233                 Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send");
234                 while(true) {
235                     if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
236                     for(Mailbox.Iterator it = spool.iterator(); it.next(); ) {
237                         try {
238                             if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
239                             if (attempt(it.cur())) it.delete();
240                         } catch (Exception e)   {
241                             if (e instanceof InterruptedException) throw e;
242                             Log.error(SMTP.Outgoing.class, e);
243                         }
244                     }
245                     synchronized(Outgoing.class) {
246                         if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
247                         Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep");
248                         Outgoing.class.wait(5 * 60 * 1000);
249                         deadHosts.clear();
250                         Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue");
251                     }
252                 }
253             } catch (Exception e) {
254                 Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e);
255                 Log.error(SMTP.Outgoing.class, e);
256             }
257         }
258     }
259
260     public static InetAddress[] getMailExchangerIPs(String hostName) {
261         InetAddress[] ret;
262         try {
263             Hashtable env = new Hashtable();
264             env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
265             DirContext ictx = new InitialDirContext(env);
266             Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
267             Attribute attr = attrs.get("MX");
268             if (attr == null) {
269                 ret = new InetAddress[1];
270                 try {
271                     ret[0] = InetAddress.getByName(hostName);
272                     return ret;
273                 } catch (UnknownHostException uhe) {
274                     Log.warn(SMTP.class, "no MX hosts or A record for " + hostName);
275                     return new InetAddress[0];
276                 }
277             } else {
278                 ret = new InetAddress[attr.size()];
279                 NamingEnumeration ne = attr.getAll();
280                 for(int i=0; ne.hasMore(); i++) {
281                     String mx = (String)ne.next();
282                     // FIXME we should be sorting here
283                     mx = mx.substring(mx.indexOf(" ") + 1);
284                     if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1);
285                     ret[i] = InetAddress.getByName(mx);
286                 }
287             }
288         } catch (Exception e) {
289             Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to");
290             Log.warn(SMTP.class, e);
291             return new InetAddress[0];
292         }
293         return ret;
294     }
295 }