X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=src%2Forg%2Fibex%2Fmail%2Fprotocol%2FSMTP.java;h=af62e214bb550bbb6c76e036924808d82ceee7e9;hb=4ff26332350edaa3c6ebfa29408c61412a6a2e40;hp=8261247be8f9c8f27497817ab13b61eff51bc978;hpb=6e7e40e7100de89b4ad91d63aafa856f7d5e418d;p=org.ibex.mail.git diff --git a/src/org/ibex/mail/protocol/SMTP.java b/src/org/ibex/mail/protocol/SMTP.java index 8261247..af62e21 100644 --- a/src/org/ibex/mail/protocol/SMTP.java +++ b/src/org/ibex/mail/protocol/SMTP.java @@ -1,7 +1,13 @@ +// Copyright 2000-2005 the Contributors, as shown in the revision logs. +// Licensed under the Apache Public Source License 2.0 ("the License"). +// You may not use this file except in compliance with the License. + package org.ibex.mail.protocol; import org.ibex.mail.*; import org.ibex.mail.target.*; import org.ibex.util.*; +import org.ibex.net.*; +import org.ibex.io.*; import java.net.*; import java.io.*; import java.util.*; @@ -9,264 +15,381 @@ import java.text.*; import javax.naming.*; import javax.naming.directory.*; -public class SMTP extends MessageProtocol { +// 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: 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 { + for(int i=0; i") ? null : new Address(command); + conn.println("250 " + from + " is syntactically correct"); + } else if (c.startsWith("RCPT TO:")) { + // some clients are broken and put RCPT first; we will tolerate this + command = command.substring(8).trim(); + if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' ')); + Address addr = new Address(command); + /* + Log.warn("**"+conn.getRemoteAddress()+"**", + "addr.isLocal(): " + addr.isLocal() + "\n" + + "conn.getRemoteAddress().isLoopbackAddress(): " + conn.getRemoteAddress().isLoopbackAddress() + "\n" + + "johnw: " + (from!=null&&from.toString().indexOf("johnw")!=-1) + "\n" + ); + */ + if (addr.isLocal()) { + // FEATURE: should check the address further and give 550 if undeliverable + conn.println("250 " + addr + " is on this machine; I will deliver it"); + to.addElement(addr); + } else if (conn.getRemoteAddress().isLoopbackAddress() || (from!=null&&from.toString().indexOf("johnw")!=-1)) { + conn.println("250 you are connected locally, so I will let you send"); + to.addElement(addr); + } else { + conn.println("551 sorry, " + addr + " is not on this machine"); + } + conn.flush(); + } else if (c.startsWith("DATA")) { + //if (from == null) { conn.println("503 MAIL FROM command must precede DATA"); continue; } + if (to == null || to.size()==0) { conn.println("503 RCPT TO command must precede DATA"); continue; } + if (!graylist.isWhitelisted(conn.getRemoteAddress()) && !conn.getRemoteAddress().isLoopbackAddress()) { + long when = graylist.getGrayListTimestamp(conn.getRemoteAddress(), from+"", to+""); + if (when == 0 || System.currentTimeMillis() - when > 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(); + buf.append("Received: from " + conn.getRemoteHostname() + " (" + remotehost + ")\r\n"); + buf.append(" by "+conn.vhost+" ("+SMTP.class.getName()+") with "+(ehlo?"ESMTP":"SMTP") + "\r\n"); + buf.append(" for "); + // FIXME: this is leaking BCC addrs + // for(int i=0; i 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; + for(int i=0; i= 100) { - Log.warn(SMTP.Outgoing.class, - "Message with " + m.traces.length + " trace hops; silently dropping\n" + m.summary()); - return; + 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; } + 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) { - outgoing.add(m); - queue.append(m); - Outgoing.class.notify(); + spool.add(m); + Outgoing.class.notifyAll(); } } - // FIXME!!! ignores more than one destination envelope!!!! - private static boolean attempt(Message m) throws IOException { - InetAddress[] mx = getMailExchangerIPs(m.envelopeTo[0].host); + 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[0].host + "; bouncing it\n" + m.summary()); - send(m.bounce("could not resolve " + m.envelopeTo[0].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()); - send(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 3 && s.charAt(3) == '-') s = conn.readln(); + if (s.startsWith("4")||s.startsWith("5")) throw new SMTPException(s); + } + private static boolean attempt(final Message m, final InetAddress mx) { + boolean accepted = false; + Connection conn = null; try { - String vhost = InetAddress.getLocalHost().getHostName(); - String cid = getConversation(); - PrintWriter logf = new PrintWriter(new OutputStreamWriter(new FileOutputStream(convdir+File.separatorChar+cid))); - Log.setThreadAnnotation("[outgoing smtp: " + mx + " / " + cid + "] "); - Log.info(SMTP.Outgoing.class, "connecting..."); - Socket s = new Socket(mx, 25); - Log.info(SMTP.Outgoing.class, "connected"); - LineReader r = new LoggedLineReader(new InputStreamReader(s.getInputStream()), logf); - PrintWriter w = new LoggedPrintWriter(new OutputStreamWriter(s.getOutputStream()), logf); - check(r.readLine()); // banner - w.print("HELO " + vhost + "\r\n"); check(r.readLine()); - w.print("MAIL FROM: " + m.envelopeFrom + "\r\n"); check(r.readLine()); - w.print("RCPT TO: " + m.envelopeTo + "\r\n"); check(r.readLine()); - w.print("DATA\r\n"); check(r.readLine()); - w.print(m.body); - w.print(".\r\n"); - check(r.readLine()); - Log.info(SMTP.Outgoing.class, "message accepted by " + mx); - // FIXME! - //outgoing.delete(m); - s.close(); - return true; + Log.note("connecting to " + mx + "..."); + conn = new Connection(new Socket(mx, 25), InetAddress.getLocalHost().getHostName()); + conn.setNewline("\r\n"); + conn.setTimeout(60 * 1000); + Log.note(" connected"); + check(conn.readln(), conn); // banner + try { + conn.println("EHLO " + conn.vhost); + check(conn.readln(), conn); + } catch (SMTPException smtpe) { + conn.println("HELO " + conn.vhost); + check(conn.readln(), conn); + } + if (m.envelopeFrom==null) { + Log.warn("", "MAIL FROM:<>"); + conn.println("MAIL FROM:<>"); check(conn.readln(), conn); + } else { + Log.warn("", "MAIL FROM:<" + m.envelopeFrom.toString()+">"); + conn.println("MAIL FROM:<" + m.envelopeFrom.toString()+">"); check(conn.readln(), conn); + } + conn.println("RCPT TO:<" + m.envelopeTo.toString()+">"); check(conn.readln(), conn); + conn.println("DATA"); check(conn.readln(), conn); + Headers head = m.headers; + 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("."); + conn.println(s); + } + conn.println(""); + stream = m.getBody().getStream(); + for(String s = stream.readln(); s!=null; s=stream.readln()) { + if (s.startsWith(".")) conn.print("."); + conn.println(s); + } + conn.println("."); + String resp = conn.readln(); + if (resp == null) + throw new SMTPException("server " + mx + " closed connection without accepting message"); + check(resp, conn); + 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) { - Log.warn(SMTP.Outgoing.class, "unable to send; error=" + 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 (conn != null) Log.warn(SMTP.Outgoing.class, conn.dumpLog()); return false; } finally { - Log.setThreadAnnotation("[outgoing smtp] "); + if (conn != null) conn.close(); + } + return accepted; + } + + 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); } } - static void runq() { + 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; " + outgoing.count(Query.all()) + " messages to send"); - for(Mailbox.Iterator it = outgoing.iterator(); it.cur() != null; it.next()) queue.append(it.cur()); while(true) { - int num = queue.size(); - for(int i=0; i