cb430396946b654ecff4602762e10716bc704681
[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         this.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 (this.messageid == null)
82             throw new RuntimeException("every RFC2822 message must have a Message-ID: header");
83     }
84
85
86     // Helpers /////////////////////////////////////////////////////////////////////////////
87
88     // http://www.jwz.org/doc/mid.html
89     private static final Random random = new Random();
90     public static String generateFreshMessageId() {
91         return generateFreshMessageId(Base36.encode(System.currentTimeMillis())+'.'+
92                                       Base36.encode(random.nextLong()));
93     }
94     // FEATURE: sha1-based deterministic messageids?  probably only useful for some virtual Mailbox impls though
95     public static String generateFreshMessageId(String seed) {
96         StringBuffer ret = new StringBuffer();
97         ret.append('<');
98         ret.append(seed);
99         ret.append('@');
100         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
101         ret.append('>');
102         return ret.toString();
103     }
104
105     // FIXME: untested.  Do we really want to duplicate all the old headers???
106     public Message reply(Fountain body, Address from, boolean includeReInSubject) throws Malformed {
107         return reply(new String[0], body, from, includeReInSubject);
108     }
109     public Message reply(String[] keyval, Fountain body, Address envelopeFrom, boolean includeReInSubject) throws Malformed {
110         Address to = null;
111         if (to==null) to = Address.parse(headers.get("reply-to"));
112         if (to==null) to = Address.parse(headers.get("from"));
113         if (to==null) to = this.envelopeFrom;
114         if (to==null) throw new Malformed("cannot reply to a message without a return address");
115         String references = headers.get("references");
116         String subject = this.subject;
117         if (includeReInSubject && subject!=null && !subject.toLowerCase().trim().startsWith("re:"))
118             subject = "Re: "+subject;
119         Headers h = new Headers(new Headers(new String[] {
120             "To",          to.toString(true),
121             "Message-Id",  generateFreshMessageId(),
122             "Date",        new Date()+"" /*FIXME!!!*/,
123             "Subject",     subject,
124             "In-Reply-To", messageid,
125             "References",  messageid + (references==null?"":(" "+references))
126             }), keyval);
127         return newMessageFromHeadersAndBody(h, body, from, to);
128     }
129
130     // this is belived to be compliant with QSBMF (http://cr.yp.to/proto/qsbmf.txt)
131     public Message bounce(String reason) {
132         if (envelopeFrom==null || envelopeFrom.toString().equals("")) return null;
133
134         // FIXME: limit bounce body size
135         // FIXME: include headers from  bounced message
136         Log.warn(Message.class, "bouncing message due to: " + reason);
137         Headers h = new Headers(headers, new String[] {
138             "Envelope-To", envelopeFrom.toString(),
139             "Return-Path", "<>",
140             "From",        "MAILER-DAEMON <>",
141             "To",          envelopeFrom.toString(),
142             "Subject",     "failure notice"
143         });
144
145         String error =
146             "\r\n"+
147             "Hi. This is the Ibex Mail Server.  I'm afraid I wasn't able to deliver\r\n"+
148             "your message to the following addresses. This is a permanent error;\r\n"+
149             "I've given up.  Sorry it didn't work out\r\n."+
150             "\r\n"+
151             "<"+envelopeTo.toString()+">:\r\n"+
152             reason+"\r\n"+
153             "\r\n"+
154             "--- Below this line is a copy of the message.\r\n"+
155             "\r\n";
156
157         try {
158             return newMessage(Fountain.Util.concat(h, Fountain.Util.create(error), getBody()));
159         } catch (Message.Malformed e) {
160             Log.error(this, "caught Message.Malformed in Message.bounce(); this should never happen");
161             Log.error(this, e);
162             return null;
163         }
164     }
165
166     public       String toString() { throw new RuntimeException("Message.toString() called"); }
167     public final String summary() { return "[" + envelopeFrom + " -> " + envelopeTo + "] " + subject; }
168
169     public static class Malformed extends MailException { public Malformed(String s) { super(s); } }
170 }
171