some header comments in Message
[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 // FIXME: body constraints (how to enforce?)
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 // FEATURE: PGP-signature-parsing
21 // FEATURE: mailing list header parsing (?)
22 // FEATURE: threading as in http://www.jwz.org/doc/threading.html
23
24 /** 
25  *  [immutable] This class encapsulates a message "floating in the
26  *  ether": RFC2822 data but no storage-specific flags or other
27  *  metadata.
28  */
29 public class Message extends MIME.Part {
30
31     // Parsed Headers //////////////////////////////////////////////////////////////////////////////
32
33     public final Address     to;
34     public final Address     from;                // if multiple From entries, this is sender
35     public final Address     envelopeFrom;
36     public final Address     envelopeTo;
37     public final Date        date;
38     public final Date        arrival;
39     public final Address     replyto;             // if none provided, this is equal to sender
40     public final String      subject;
41     public final String      messageid;
42     public final Address[]   cc;
43     public final Address[]   bcc;
44
45     public static Message newMessage(Fountain in) throws Malformed { return new Message(in); }
46
47     public Message reply(Fountain in, Address from, boolean includeReInSubject) throws Malformed {
48         /*
49         Address to = null;
50         if (to==null) to = Address.parse(headers.get("reply-to"));
51         if (to==null) to = Address.parse(headers.get("from"));
52         if (to==null) to = envelopeFrom;
53         Message ret = newMessage(in, from, to);
54         ret.headers.put("In-Reply-To", messageid);
55         String references = headers.get("references");
56         ret.headers.put("References", messageid + (references==null?"":(" "+references)));
57         if (includeReInSubject && subject!=null && !subject.toLowerCase().trim().startsWith("re:"))
58             headers.put("subject", "Re: "+subject);
59         return ret;
60         */
61         // FIXME
62         return null;
63     }
64
65     // FIXME
66     //public static Message newMessage(Headers headers, Fountain body, Address from, Address to) throws Malformed {
67     //}
68
69     public static Message newMessage(Fountain in, Address from, Address to) throws Malformed {
70         StringBuffer sb = new StringBuffer();
71         if (from != null) sb.append("Return-Path: " + from.toString(true) + "\r\n");
72         Stream stream = in.getStream();
73         while(true) {
74             String s = stream.readln();
75             if (s == null || s.length() == 0) {
76                 if (to != null) sb.append("Envelope-To: " + to.toString(true) + "\r\n");
77                 sb.append("\r\n");
78                 break;
79             }
80             if (to != null && s.toLowerCase().startsWith("envelope-to:")) continue;
81             if (s.toLowerCase().startsWith("return-path:")) continue;
82             sb.append(s);
83             sb.append("\r\n");
84         }
85         for(String s = stream.readln(); s != null; s = stream.readln()) {
86             sb.append(s);
87             sb.append("\r\n");
88         }
89         return new Message(new Fountain.StringFountain(sb.toString()));
90     }
91
92     private Message(Fountain in) throws Malformed {
93         super(in);
94
95         this.envelopeTo   = headers.get("Envelope-To") != null ? Address.parse(headers.get("Envelope-To")) : null;
96         this.envelopeFrom = headers.get("Return-Path") != null ? Address.parse(headers.get("Return-Path")) : null;
97         this.to           = headers.get("To") != null ? Address.parse(headers.get("To")) : this.envelopeTo;
98         this.from         = headers.get("From") != null ? Address.parse(headers.get("From")) : this.envelopeFrom;
99         this.replyto      = headers.get("Reply-To") == null ? null : Address.parse(headers.get("Reply-To"));
100         this.subject      = headers.get("Subject");
101         this.messageid    = headers.get("Message-Id");
102         this.cc           = Address.list(headers.get("Cc"));
103         this.bcc          = Address.list(headers.get("Bcc"));
104         this.date         = parseDate(headers.get("Date")) == null ? new Date() : parseDate(headers.get("Date"));
105
106         // reenable this once whitelisting is moved out of javascript
107         //if (this.messageid==null)
108         //throw new RuntimeException("every RFC2822 message must have a Message-ID: header");
109
110         /*
111         // synthesize a message-id if not provided
112         this.messageid    = headers.get("Message-Id") == null ? generateFreshMessageId(sha1(in.getStream())) : headers.get("Message-Id");
113         if (headers.get("Message-Id") == null) {
114             headers = headers.set("Message-Id", this.messageid);
115             Log.warn(Message.class, "synthesizing message-id for " + summary());
116         }
117         */
118
119         this.arrival      = this.date; // FIXME wrong; grab this from traces?
120     }
121
122     /*
123     private static String sha1(Stream stream) {
124         SHA1 sha1 = new SHA1();
125         byte[] b = new byte[1024];
126         while(true) {
127             int numread = stream.read(b, 0, b.length);
128             if (numread == -1) break;
129             sha1.update(b, 0, numread);
130         }
131         byte[] results = new byte[sha1.getDigestSize()];
132         sha1.doFinal(results, 0);
133         return new String(Encode.toBase64(results));
134     }
135     */
136
137     // Helpers /////////////////////////////////////////////////////////////////////////////
138
139     // http://www.jwz.org/doc/mid.html
140     private static final Random random = new Random();
141     public static String generateFreshMessageId() {
142         return generateFreshMessageId(Base36.encode(System.currentTimeMillis())+'.'+
143                                       Base36.encode(random.nextLong()));
144     }
145     public static String generateFreshMessageId(String seed) {
146         StringBuffer ret = new StringBuffer();
147         ret.append('<');
148         ret.append(seed);
149         ret.append('@');
150         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
151         ret.append('>');
152         return ret.toString();
153     }
154
155     public static Date parseDate(String s) {
156         // FIXME!!! this must be robust
157         // date/time parsing: see spec, 3.3
158         return null;
159     }
160
161     // this is belived to be compliant with QSBMF (http://cr.yp.to/proto/qsbmf.txt)
162     public Message bounce(String reason) {
163         if (envelopeFrom==null || envelopeFrom.toString().equals("")) return null;
164
165         Log.warn(Message.class, "bouncing message due to: " + reason);
166         Headers h = new Headers.Original(headers.getStream());
167         h = h.set(new String[] {
168             "Envelope-To", envelopeFrom.toString(),
169             "Return-Path", "<>",
170             "From",        "MAILER-DAEMON <>",
171             "To",          envelopeFrom.toString(),
172             "Subject",     "failure notice"
173         });
174
175         String error =
176             "Hi. This is the Ibex Mail Server.  I'm afraid I wasn't able to deliver\r\n"+
177             "your message to the following addresses. This is a permanent error;\r\n"+
178             "I've given up.  Sorry it didn't work out\r\n."+
179             "\r\n"+
180             "<"+envelopeTo.toString()+">:\r\n"+
181             reason+"\r\n"+
182             "\r\n"+
183             "--- Below this line is a copy of the message.\r\n"+
184             "\r\n";
185
186         try {
187             return newMessage(new Fountain.Concatenate(new Fountain.StringFountain(h.getString()+"\r\n"+error), getBody()));
188         } catch (Message.Malformed e) {
189             Log.error(this, "caught Message.Malformed in Message.bounce(); this should never happen");
190             Log.error(this, e);
191             return null;
192         }
193     }
194
195     public       String toString() { throw new RuntimeException("Message.toString() called"); }
196     public final String summary() { return "[" + envelopeFrom + " -> " + envelopeTo + "] " + subject; }
197
198     public static class Malformed extends MailException { public Malformed(String s) { super(s); } }
199 }
200