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.
6 import org.ibex.crypto.*;
7 import org.ibex.util.*;
8 import org.ibex.mail.protocol.*;
11 import org.ibex.io.Fountain;
16 // FEATURE: body constraints (how to enforce without reading stream, though?)
17 // - messages must NEVER contain 8-bit binary data; this is a violation of IMAP
18 // - RFC822 1,000-char limit per line [soft line limit (suggested): 78 chars / hard line limit: 998 chars]
21 * [immutable] This class encapsulates a message "floating in the
22 * ether": RFC2822 data but no storage-specific flags or other
25 public class Message extends MIME.Part {
27 // Parsed Headers //////////////////////////////////////////////////////////////////////////////
29 public final Address to;
30 public final Address from; // if multiple From entries, this is sender
31 public final Address envelopeFrom;
32 public final Address envelopeTo;
33 public final Date date;
34 public final Date arrival;
35 public final Address replyto; // if none provided, this is equal to sender
36 public final String subject;
37 public final String messageid;
38 public final Address[] cc;
39 public final Address[] bcc;
41 public static Message newMessage(Fountain in) throws Malformed { return new Message(in, null); }
42 public static Message newMessageFromHeadersAndBody(Headers head, Fountain body, Address from, Address to) throws Malformed {
43 return new Message(Fountain.Util.concat(head, Fountain.Util.create("\r\n"), body),
45 "Return-Path", from==null ? "<>" : from.toString(true),
46 "Envelope-To", to.toString(true)
50 public static Message newMessageWithEnvelope(Fountain in, Address from, Address to) throws Malformed {
51 return new Message(in,
53 "Return-Path", from==null ? "<>" : from.toString(true),
54 "Envelope-To", to.toString(true)
58 public Message withEnvelope(Address from, Address to) {
59 return new Message(this,
61 "Return-Path", from==null ? "<>" : from.toString(true),
62 "Envelope-To", to.toString(true)
65 private Message(Fountain in, String[] keyval) throws Malformed {
68 this.envelopeTo = headers.get("Envelope-To") != null ? Address.parse(headers.get("Envelope-To")) : null;
69 this.envelopeFrom = headers.get("Return-Path") != null ? Address.parse(headers.get("Return-Path")) : null;
70 this.to = headers.get("To") != null ? Address.parse(headers.get("To")) : this.envelopeTo;
71 this.from = headers.get("From") != null ? Address.parse(headers.get("From")) : this.envelopeFrom;
72 this.replyto = headers.get("Reply-To") == null ? null : Address.parse(headers.get("Reply-To"));
73 this.subject = headers.get("Subject");
74 String messageid = headers.get("Message-Id");
75 this.cc = Address.list(headers.get("Cc"));
76 this.bcc = Address.list(headers.get("Bcc"));
77 Date date = RobustDateParser.parseDate(headers.get("Date"));
78 this.date = date==null ? new Date() : date;
79 this.arrival = this.date; // FIXME wrong: should grab this from traces, I think?
81 if (messageid == null) {
82 SHA1 sha1 = new SHA1();
83 Stream s = this.getStream();
84 s.setInputDigest(sha1);
85 s.transcribe(new Stream(new NullOutputStream()));
86 byte[] end = new byte[sha1.getDigestSize()];
88 messageid = "<synthetic.messageid." + Encode.toBase64String(end) + ">";
89 Log.info(this, "synthesized messageid " + messageid);
91 this.messageid = messageid;
95 // Helpers /////////////////////////////////////////////////////////////////////////////
97 // http://www.jwz.org/doc/mid.html
98 private static final Random random = new Random();
99 public static String generateFreshMessageId() {
100 return generateFreshMessageId(Base36.encode(System.currentTimeMillis())+'.'+
101 Base36.encode(random.nextLong()));
103 // FEATURE: sha1-based deterministic messageids? probably only useful for some virtual Mailbox impls though
104 public static String generateFreshMessageId(String seed) {
105 StringBuffer ret = new StringBuffer();
109 try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
111 return ret.toString();
114 // FIXME: untested. Do we really want to duplicate all the old headers???
115 public Message reply(Fountain body, Address from, boolean includeReInSubject) throws Malformed {
116 return reply(new String[0], body, from, includeReInSubject);
118 public Message reply(String[] keyval, Fountain body, Address envelopeFrom, boolean includeReInSubject) throws Malformed {
120 if (to==null) to = Address.parse(headers.get("reply-to"));
121 if (to==null) to = Address.parse(headers.get("from"));
122 if (to==null) to = this.envelopeFrom;
123 if (to==null) throw new Malformed("cannot reply to a message without a return address");
124 String references = headers.get("references");
125 String subject = this.subject;
126 if (includeReInSubject && subject!=null && !subject.toLowerCase().trim().startsWith("re:"))
127 subject = "Re: "+subject;
128 Headers h = new Headers(new Headers(new String[] {
129 "To", to.toString(true),
130 "Message-Id", generateFreshMessageId(),
131 "Date", new Date()+"" /*FIXME!!!*/,
133 "In-Reply-To", messageid,
134 "References", messageid + (references==null?"":(" "+references))
136 return newMessageFromHeadersAndBody(h, body, from, to);
139 // this is belived to be compliant with QSBMF (http://cr.yp.to/proto/qsbmf.txt)
140 public Message bounce(String reason) {
141 if (envelopeFrom==null || envelopeFrom.toString().equals("")) return null;
143 // FIXME: limit bounce body size
144 // FIXME: include headers from bounced message
145 Log.warn(Message.class, "bouncing message due to: " + reason);
146 Headers h = new Headers(headers, new String[] {
147 "Envelope-To", envelopeFrom.toString(),
149 "From", "MAILER-DAEMON <>",
150 "To", envelopeFrom.toString(),
151 "Subject", "failure notice"
156 "Hi. This is the Ibex Mail Server. I'm afraid I wasn't able to deliver\r\n"+
157 "your message to the following addresses. This is a permanent error;\r\n"+
158 "I've given up. Sorry it didn't work out\r\n."+
160 "<"+envelopeTo.toString()+">:\r\n"+
163 "--- Below this line is a copy of the message.\r\n"+
167 return newMessage(Fountain.Util.concat(h, Fountain.Util.create(error), getBody()));
168 } catch (Message.Malformed e) {
169 Log.error(this, "caught Message.Malformed in Message.bounce(); this should never happen");
175 public String toString() { throw new RuntimeException("Message.toString() called"); }
176 public final String summary() { return "[" + envelopeFrom + " -> " + envelopeTo + "] " + subject; }
178 public static class Malformed extends MailException { public Malformed(String s) { super(s); } }
180 /** reads an SMTP-style dot-escaped message */
181 static Message readDotEncodedMessage(Stream conn) {
182 StringBuffer buf = new StringBuffer();
184 String s = conn.readln();
185 if (s == null) throw new RuntimeException("connection closed");
186 if (s.equals(".")) break;
187 if (s.startsWith(".")) s = s.substring(1);
191 return Message.newMessage(new Fountain.StringFountain(buf.toString()));