X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=src%2Forg%2Fibex%2Fmail%2Fprotocol%2FSMTP.java;h=18d49dbd8f116a3a46adb2c40f7b62c505a44c7a;hb=0704cf17772a0cfe704e8d379723e96137d7da95;hp=85d539053d1923b5f18aac67827429f2cd78ac85;hpb=03ba920b245d6395b5139000ea5461d9eee0116a;p=org.ibex.mail.git diff --git a/src/org/ibex/mail/protocol/SMTP.java b/src/org/ibex/mail/protocol/SMTP.java index 85d5390..18d49db 100644 --- a/src/org/ibex/mail/protocol/SMTP.java +++ b/src/org/ibex/mail/protocol/SMTP.java @@ -1,134 +1,340 @@ +// 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.store.*; 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.*; +import java.text.*; +import javax.naming.*; +import javax.naming.directory.*; -public class SMTP extends MessageProtocol { +// 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 +// FEATURE: infer messageid, date, if not present (?) +// 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 SMTP() {/* setProtocolName("SMTP"); */} - //public ServerRequest createRequest(Connection conn) { return new Listener((TcpConnection)conn); } + public static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); + private static final Mailbox spool = + FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT,false).slash("spool",true).slash("smtp",true); - public static class Outgoing { - // recommended retry interval is 30 minutes - // give up after 4-5 days - // should keep per-host success/failure so we don't retry on every message - // exponential backoff on retry time? - // check DNS resolvability as soon as domain is provided - // only use implicit A-record if there are no MX-records - // use null-sender for error messages (don't send errors to the null addr) - // to prevent mail loops, drop messages with >100 Recieved headers - private final org.ibex.util.Queue queue = new org.ibex.util.Queue(100); - public static void send(Message m) { } - public static void enqueue(Message m) { } - public static void bounce(Message m, String reason) { } - private void runq() { - /* - MessageStore store = MessageStore.root.slash("smtp").slash("outgoing"); - int[] outgoing = store.list(); - 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(' ')); - from = new Message.Address(command); - - } else if (command.toUpperCase().startsWith("RCPT TO:")) { - if (from == null) { - ws.println("503 MAIL FROM must precede RCPT TO"); - continue; + Address addr = new Address(command); + 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()) { + 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"); } - command = command.substring(10).trim(); - if(command.indexOf(' ') != -1) command = command.substring(0, command.indexOf(' ')); - to.addElement(new Message.Address(command)); - - } else if (command.toUpperCase().startsWith("DATA")) { - if (from == null) { ws.println("503 MAIL FROM command must precede DATA"); continue; } - if (to == null) { ws.println("503 RCPT TO command must precede DATA"); continue; } - ws.println("354 Enter message, ending with \".\" on a line by itself"); - StringBuffer data = new StringBuffer(); - // move this into the Message class - boolean good = false; + } 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; } + conn.println("354 Enter message, ending with \".\" on a line by itself"); + conn.flush(); try { - good = true; - Message m = new Message(rs, true); - accept(m); - } finally { - //ws.println("251 user not local; will forward"); - if (good) ws.println("250 OK message accepted for delivery"); - else { /* FIXME */ } + 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= 100) + Log.warn(SMTP.Outgoing.class, "Message with " + m.traces.length + " trace hops; dropping\n" + m.summary()); + */ + else synchronized(Outgoing.class) { + spool.add(m); + Outgoing.class.notify(); + } + } + + public static boolean attempt(Message m) 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 (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; + } + 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 { + 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 { - ws.println("500 unrecognized command"); - } - + 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.remove("return-path"); + 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("."); + 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 { + accept(m.bounce("unable to deliver: " + e)); + } catch (Exception ex) { + Log.error(SMTP.Outgoing.class, "very serious: exception while trying to deliver bounce"); + 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); + 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 { + if (conn != null) conn.close(); + } + return accepted; + } + + static void runq() { + 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); + } + } + 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"); + } + } + } catch (Exception e) { + Log.error(SMTP.Outgoing.class, "outgoing thread killed by exception: " + e); + Log.error(SMTP.Outgoing.class, e); + } + } + } + + public static InetAddress[] getMailExchangerIPs(String hostName) { + InetAddress[] ret; + try { + Hashtable env = new Hashtable(); + env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); + DirContext ictx = new InitialDirContext(env); + Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" }); + Attribute attr = attrs.get("MX"); + if (attr == null) { + ret = new InetAddress[1]; + try { + ret[0] = InetAddress.getByName(hostName); + return ret; + } catch (UnknownHostException uhe) { + Log.warn(SMTP.class, "no MX hosts or A record for " + hostName); + return new InetAddress[0]; + } + } else { + ret = new InetAddress[attr.size()]; + NamingEnumeration ne = attr.getAll(); + for(int i=0; ne.hasMore();) { + String mx = (String)ne.next(); + // FIXME we should be sorting here + 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; + ret[i++] = ia; + } } - return false; // FIXME: what does this mean? + } catch (Exception e) { + Log.warn(SMTP.class, "couldn't find MX host for " + hostName + " due to"); + Log.warn(SMTP.class, e); + return new InetAddress[0]; } + return ret; } }