X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=src%2Forg%2Fibex%2Fmail%2Fprotocol%2FSMTP.java;h=af62e214bb550bbb6c76e036924808d82ceee7e9;hb=4ff26332350edaa3c6ebfa29408c61412a6a2e40;hp=32c25f689a76d7f48160eb23ddd46e4cca694d78;hpb=3c9e025ab5e55a830d6e4f3264f26bd245cb25ef;p=org.ibex.mail.git diff --git a/src/org/ibex/mail/protocol/SMTP.java b/src/org/ibex/mail/protocol/SMTP.java index 32c25f6..af62e21 100644 --- a/src/org/ibex/mail/protocol/SMTP.java +++ b/src/org/ibex/mail/protocol/SMTP.java @@ -15,21 +15,40 @@ import java.text.*; import javax.naming.*; import javax.naming.directory.*; -// FIXME: bounce messages (must go to return-path unless empty, in which case do not send -// FIXME: if more than 100 "Received" lines, must drop message +// FIXME: logging: current logging sucks +// FIXME: loop prevention +// FIXME: probably need some throttling on outbound mail + // FEATURE: infer messageid, date, if not present (?) +// FEATURE: exponential backoff on retry time? // FEATURE: RFC2822, section 4.5.1: special "postmaster" address // FEATURE: RFC2822, section 4.5.4.1: retry strategies // FEATURE: RFC2822, section 5, multiple MX records, preferences, ordering -// FEATURE: exponential backoff on retry time? // FEATURE: RFC2822, end of 4.1.2: backslashes in headers public class SMTP { public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); + public static final int numOutgoingThreads = 5; + + public static final int GRAYLIST_MINWAIT = 1000 * 60 * 60; // one hour + public static final int GRAYLIST_MAXWAIT = 1000 * 60 * 60 * 24 * 5; // five days + + public static final Graylist graylist = + new Graylist(Mailbox.STORAGE_ROOT+"/db/graylist.sqlite"); + + public static final Whitelist whitelist = + new Whitelist(Mailbox.STORAGE_ROOT+"/db/whitelist.sqlite"); + + public static final int MAX_MESSAGE_SIZE = + Integer.parseInt(System.getProperty("org.ibex.mail.smtp.maxMessageSize", "-1")); + private static final Mailbox spool = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true); - static { new Thread() { public void run() { Outgoing.runq(); } }.start(); } + static { + for(int i=0; i GRAYLIST_MAXWAIT) { + graylist.setGrayListTimestamp(conn.getRemoteAddress(), from+"", to+"", System.currentTimeMillis()); + conn.println("451 you are graylisted; please try back in one hour to be whitelisted"); + Log.warn(conn.getRemoteAddress().toString(), "451 you are graylisted; please try back in one hour to be whitelisted"); + conn.flush(); + continue; + } else if (System.currentTimeMillis() - when > GRAYLIST_MINWAIT) { + graylist.addWhitelist(conn.getRemoteAddress()); + conn.println("354 (you have been whitelisted) Enter message, ending with \".\" on a line by itself"); + Log.warn(conn.getRemoteAddress().toString(), "has been whitelisted"); + } else { + conn.println("451 you are still graylisted (since "+new java.util.Date(when)+")"); + conn.flush(); + Log.warn(conn.getRemoteAddress().toString(), "451 you are still graylisted (since "+new java.util.Date(when)+")"); + continue; + } + } else { + conn.println("354 Enter message, ending with \".\" on a line by itself"); + } conn.flush(); try { StringBuffer buf = new StringBuffer(); @@ -119,6 +167,13 @@ public class SMTP { if (s.equals(".")) break; if (s.startsWith(".")) s = s.substring(1); buf.append(s + "\r\n"); + if (MAX_MESSAGE_SIZE != -1 && buf.length() > MAX_MESSAGE_SIZE) { + Log.error("**"+conn.getRemoteAddress()+"**", + "sorry, this mail server only accepts messages of less than " + + ByteSize.toString(MAX_MESSAGE_SIZE)); + throw new MailException.Malformed("sorry, this mail server only accepts messages of less than " + + ByteSize.toString(MAX_MESSAGE_SIZE)); + } } String body = buf.toString(); Message m = null; @@ -130,14 +185,12 @@ public class SMTP { conn.println("250 message accepted"); conn.flush(); from = null; to = new Vector(); + } catch (Reject.RejectException re) { + Log.warn(SMTP.class, "rejecting message due to: " + re.reason + "\n " + re.m.summary()); + conn.println("501 " + re.reason); } catch (MailException.Malformed mfe) { conn.println("501 " + mfe.toString()); } catch (MailException.MailboxFull mbf) { conn.println("452 " + mbf); } catch (Later.LaterException le) { conn.println("453 try again later"); - } catch (IOException ioe) { - //conn.println("554 " + ioe.toString()); - Log.error(this, ioe); - conn.close(); - return; } } else { conn.println("500 unrecognized command"); } } catch (Message.Malformed e) { conn.println("501 " + e.toString()); } @@ -147,40 +200,55 @@ public class SMTP { // Outgoing Mail Thread ////////////////////////////////////////////////////////////////////////////// - public static class Outgoing { + public static class Outgoing extends Thread { - private static final HashSet deadHosts = new HashSet(); + private static final HashMap deadHosts = new HashMap(); public static void accept(Message m) throws IOException { if (m == null) { Log.warn(Outgoing.class, "attempted to accept(null)"); return; } - //Log.info(SMTP.class, "queued: " + m.summary()); - /* - if (m.traces.length >= 100) - Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary()); - */ - else synchronized(Outgoing.class) { + String traces = m.headers.get("Received"); + if (traces!=null) { + int lines = 0; + for(int i=0; i 100) { // required by rfc + Log.warn(SMTP.Outgoing.class, "Message with " + lines + " trace hops; dropping\n" + m.summary()); + return; + } + } + synchronized(Outgoing.class) { spool.add(m); - Outgoing.class.notify(); + Outgoing.class.notifyAll(); } } - public static boolean attempt(Message m) throws IOException { + public static boolean attempt(Message m) throws IOException { return attempt(m, false); } + public static boolean attempt(Message m, boolean noBounces) throws IOException { if (m.envelopeTo == null) { Log.warn(SMTP.Outgoing.class, "aieeee, null envelopeTo: " + m.summary()); return false; } InetAddress[] mx = getMailExchangerIPs(m.envelopeTo.host); if (mx.length == 0) { - Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host + "; bouncing it\n" + m.summary()); - accept(m.bounce("could not resolve " + m.envelopeTo.host)); - return true; + if (!noBounces) { + accept(m.bounce("could not resolve " + m.envelopeTo.host)); + return true; + } else { + Log.warn(SMTP.Outgoing.class, "could not resolve " + m.envelopeTo.host); + return false; + } } if (new Date().getTime() - m.arrival.getTime() > 1000 * 60 * 60 * 24 * 5) { - Log.warn(SMTP.Outgoing.class, "could not send message after 5 days; bouncing it\n" + m.summary()); - accept(m.bounce("could not send for 5 days")); - return true; + if (!noBounces) { + accept(m.bounce("could not send for 5 days")); + return true; + } else { + Log.warn(SMTP.Outgoing.class, "could not send for 5 days: " + m.summary()); + return false; + } } for(int i=0; i"); check(conn.readln(), conn); conn.println("DATA"); check(conn.readln(), conn); Headers head = m.headers; - head.remove("return-path"); - head.remove("bcc"); + head = head.remove("return-path"); + head = head.remove("bcc"); Stream stream = head.getStream(); for(String s = stream.readln(); s!=null; s=stream.readln()) { if (s.startsWith(".")) conn.print("."); - //Log.warn("***",s); conn.println(s); } - //Log.warn("***",""); conn.println(""); stream = m.getBody().getStream(); for(String s = stream.readln(); s!=null; s=stream.readln()) { if (s.startsWith(".")) conn.print("."); - //Log.warn("***",s); conn.println(s); } conn.println("."); @@ -242,6 +307,21 @@ public class SMTP { Log.warn(SMTP.Outgoing.class, "success: " + mx + " accepted " + m.summary() + "\n["+resp+"]"); accepted = true; conn.close(); + } catch (SMTPException e) { + if (accepted) return true; + Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e); + Log.warn(SMTP.Outgoing.class, " message: " + m.summary()); + Log.warn(SMTP.Outgoing.class, e); + if (e.code >= 500 && e.code <= 599) { + try { + attempt(m.bounce("unable to deliver: " + e), true); + } catch (Exception ex) { + Log.error(SMTP.Outgoing.class, "exception while trying to deliver bounce; giving up completely"); + Log.error(SMTP.Outgoing.class, ex); + } + return true; + } + return false; } catch (Exception e) { if (accepted) return true; Log.warn(SMTP.Outgoing.class, " unable to send; error=" + e); @@ -255,33 +335,61 @@ public class SMTP { return accepted; } - static void runq() { + private static HashSet threads = new HashSet(); + private static int serials = 1; + private int serial = serials++; + private Mailbox.Iterator it; + + public Outgoing() { + synchronized(Outgoing.class) { + threads.add(this); + } + } + + public void wake() { + int count = spool.count(Query.all()); + Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" woke up; " + count + " messages to send"); try { - Log.setThreadAnnotation("[outgoing smtp] "); - Log.info(SMTP.Outgoing.class, "outgoing thread started; " + spool.count(Query.all()) + " messages to send"); while(true) { - if (Thread.currentThread().isInterrupted()) throw new InterruptedException(); - for(Mailbox.Iterator it = spool.iterator(); it.next(); ) { - try { - if (Thread.currentThread().isInterrupted()) throw new InterruptedException(); - if (attempt(it.cur())) it.delete(); - } catch (Exception e) { - if (e instanceof InterruptedException) throw e; - Log.error(SMTP.Outgoing.class, e); - } - } + boolean good = false; synchronized(Outgoing.class) { - if (Thread.currentThread().isInterrupted()) throw new InterruptedException(); - Log.info(SMTP.Outgoing.class, "outgoing thread going to sleep"); - Outgoing.class.wait(5 * 60 * 1000); - deadHosts.clear(); - Log.info(SMTP.Outgoing.class,"outgoing thread woke up; "+spool.count(Query.all())+" messages in queue"); + it = spool.iterator(); + OUTER: for(; it.next(); ) { + for(Outgoing o : threads) + if (o!=this && o.it != null && o.it.uid()==it.uid()) + continue OUTER; + good = true; + break; + } } + if (!good) break; + try { + if (attempt(it.cur())) it.delete(); + } catch (Exception e) { + Log.error(SMTP.Outgoing.class, e); + } + Log.info(this, "sleeping for 3s..."); + Thread.sleep(3000); } } catch (Exception e) { - Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e); + //if (e instanceof InterruptedException) throw e; Log.error(SMTP.Outgoing.class, e); } + Log.info(SMTP.Outgoing.class, "outgoing thread #"+serial+" going back to sleep"); + it = null; + } + + public void run() { + try { + while(true) { + Log.setThreadAnnotation("[outgoing #"+serial+"] "); + wake(); + Thread.sleep(1000); + synchronized(Outgoing.class) { + Outgoing.class.wait(5 * 60 * 1000); + } + } + } catch (InterruptedException e) { Log.warn(this, e); } } } @@ -297,6 +405,7 @@ public class SMTP { ret = new InetAddress[1]; try { ret[0] = InetAddress.getByName(hostName); + if (ret[0].equals(IP.getIP(127,0,0,1)) || ret[0].isLoopbackAddress()) throw new UnknownHostException(); return ret; } catch (UnknownHostException uhe) { Log.warn(SMTP.class, "no MX hosts or A record for " + hostName); @@ -311,7 +420,7 @@ public class SMTP { mx = mx.substring(mx.indexOf(" ") + 1); if (mx.charAt(mx.length() - 1) == '.') mx = mx.substring(0, mx.length() - 1); InetAddress ia = InetAddress.getByName(mx); - if (ia.equals(IP.getIP(127,0,0,1))) continue; + if (ia.equals(IP.getIP(127,0,0,1)) || ia.isLoopbackAddress()) continue; ret[i++] = ia; } }