synthesize messageids when necessary
[org.ibex.mail.git] / src / org / ibex / mail / Message.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;
6 import org.ibex.crypto.*;
7 import org.ibex.util.*;
8 import org.ibex.mail.protocol.*;
9 import org.ibex.js.*;
10 import org.ibex.io.*;
11 import org.ibex.io.Fountain;
12 import java.util.*;
13 import java.net.*;
14 import java.io.*;
15
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]
19
20 /** 
21  *  [immutable] This class encapsulates a message "floating in the
22  *  ether": RFC2822 data but no storage-specific flags or other
23  *  metadata.
24  */
25 public class Message extends MIME.Part {
26
27     // Parsed Headers //////////////////////////////////////////////////////////////////////////////
28
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;
40
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),
44                            new String[] {
45                                "Return-Path", from==null ? "<>" : from.toString(true),
46                                "Envelope-To", to.toString(true)
47                            });
48     }
49     /*
50     public static Message newMessageWithEnvelope(Fountain in, Address from, Address to) throws Malformed {
51         return new Message(in,
52                            new String[] {
53                                "Return-Path", from==null ? "<>" : from.toString(true),
54                                "Envelope-To", to.toString(true)
55                            });
56     }
57     */
58     public Message withEnvelope(Address from, Address to) {
59         return new Message(this,
60                            new String[] {
61                                "Return-Path", from==null ? "<>" : from.toString(true),
62                                "Envelope-To", to.toString(true)
63                            });
64     }
65     private Message(Fountain in, String[] keyval) throws Malformed {
66         super(in, keyval);
67
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?
80
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()];
87             sha1.doFinal(end, 0);
88             messageid = "<synthetic.messageid." + Encode.toBase64String(end) + ">";
89             Log.info(this, "synthesized messageid " + messageid);
90         }
91         this.messageid = messageid;
92     }
93
94
95     // Helpers /////////////////////////////////////////////////////////////////////////////
96
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()));
102     }
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();
106         ret.append('<');
107         ret.append(seed);
108         ret.append('@');
109         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
110         ret.append('>');
111         return ret.toString();
112     }
113
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);
117     }
118     public Message reply(String[] keyval, Fountain body, Address envelopeFrom, boolean includeReInSubject) throws Malformed {
119         Address to = null;
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!!!*/,
132             "Subject",     subject,
133             "In-Reply-To", messageid,
134             "References",  messageid + (references==null?"":(" "+references))
135             }), keyval);
136         return newMessageFromHeadersAndBody(h, body, from, to);
137     }
138
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;
142
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(),
148             "Return-Path", "<>",
149             "From",        "MAILER-DAEMON <>",
150             "To",          envelopeFrom.toString(),
151             "Subject",     "failure notice"
152         });
153
154         String error =
155             "\r\n"+
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."+
159             "\r\n"+
160             "<"+envelopeTo.toString()+">:\r\n"+
161             reason+"\r\n"+
162             "\r\n"+
163             "--- Below this line is a copy of the message.\r\n"+
164             "\r\n";
165
166         try {
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");
170             Log.error(this, e);
171             return null;
172         }
173     }
174
175     public       String toString() { throw new RuntimeException("Message.toString() called"); }
176     public final String summary() { return "[" + envelopeFrom + " -> " + envelopeTo + "] " + subject; }
177
178     public static class Malformed extends MailException { public Malformed(String s) { super(s); } }
179 }
180