2aa933138bfff0482ea4479a347a15efffc93209
[org.ibex.mail.git] / src / org / ibex / mail / Message.java
1 package org.ibex.mail;
2 import org.ibex.crypto.*;
3 import org.ibex.js.*;
4 import org.ibex.util.*;
5 import org.ibex.mail.protocol.*;
6 import java.util.*;
7 import java.net.*;
8 import java.io.*;
9
10 // soft line limit (suggested): 78 chars /  hard line limit: 998 chars
11 // folded headers: can insert CRLF anywhere that whitespace appears (before the whitespace)
12 // date/time parsing: see spec, 3.3
13
14 // FIXME: messages must NEVER contain 8-bit binary data; this is a violation of IMAP
15
16 // FEATURE: PGP-signature-parsing
17 // FEATURE: mailing list header parsing
18 // FEATURE: delivery status notification (and the sneaky variety)
19 // FEATURE: threading as in http://www.jwz.org/doc/threading.html
20 // FEATURE: lazy body
21
22 /** 
23  *  [immutable] This class encapsulates a message "floating in the
24  *  ether": RFC2822 data but no storage-specific flags or other
25  *  metadata.
26  */
27 public class Message extends JSReflection {
28
29     public final String allHeaders;           // pristine headers
30     public final Hashtable headers;           // hash of headers (not including resent's and traces)
31     public final String body;                 // entire body
32     public final int lines;                   // lines in the body
33
34     public final Date date;
35     public final Address to;
36     public final Address from;        // if multiple From entries, this is sender
37     public final Address replyto;     // if none provided, this is equal to sender
38     public final String subject;
39     public final String messageid;
40     public final Address[] cc;
41     public final Address[] bcc;
42     public final Hashtable[] resent;
43     public final Trace[] traces;
44
45     public final Address envelopeFrom;
46     public final Address envelopeTo;
47
48     public final Date arrival;         // when the message first arrived at this machine; IMAP "internal date message attr"
49     
50     public void dump(OutputStream os) throws IOException {
51         Writer w = new OutputStreamWriter(os);
52         w.write("X-org.ibex.mail-envelopeFrom: " + envelopeFrom + "\r\n");
53         w.write("X-org.ibex.mail-envelopeTo: " + envelopeTo + "\r\n");
54         w.write(allHeaders);
55         w.write("\r\n");
56         w.write(body);
57         w.flush();
58     }
59
60     public class Trace {
61         final String returnPath;
62         final Element[] elements;
63         public Trace(LineReader lr) throws Trace.Malformed, IOException {
64             String retPath = lr.readLine();
65             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
66             returnPath = retPath.substring(12).trim();
67             Vec el = new Vec();
68             while(true) {
69                 String s = lr.readLine();
70                 if (s == null) break;
71                 if (!s.startsWith("Received:")) { lr.pushback(s); break; }
72                 s = s.substring(9).trim();
73                 el.addElement(new Element(s));
74             }
75             elements = new Element[el.size()];
76             el.copyInto(elements);
77         }
78         public class Element {
79              String fromDomain;
80              String fromIP;
81              String toDomain;
82              String forWhom;
83              Date date;
84             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
85                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
86             public Element(String s) throws Trace.Malformed {
87                 StringTokenizer st = new StringTokenizer(s);
88                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
89                 fromDomain = st.nextToken();
90                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
91                 toDomain = st.nextToken();
92                 // FIXME not done yet
93             }
94         }
95         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
96     }
97
98     public static class Malformed extends MailException.Malformed { public Malformed(String s) { super(s); } }
99
100     public Message(Address envelopeFrom, Address envelopeTo, String s, Date arrival)
101         { this(envelopeFrom, envelopeTo, new LineReader(new StringReader(s)), arrival); }
102     public Message(Address envelopeFrom, Address envelopeTo, LineReader rs) { this(envelopeFrom, envelopeTo, rs, null); }
103     public Message(Address envelopeFrom, Address envelopeTo, LineReader rs, Date arrival) {
104         try {
105             this.arrival = arrival == null ? new Date() : arrival;
106             this.headers = new CaseInsensitiveHash();
107             Vec envelopeToHeader = new Vec();
108             String key = null;
109             StringBuffer all = new StringBuffer();
110             Date date = null;
111             Address to = null, from = null, replyto = null;
112             String subject = null, messageid = null;
113             Vec cc = new Vec(), bcc = new Vec(), resent = new Vec(), traces = new Vec();
114             for(String s = rs.readLine(); s != null && !s.equals(""); s = rs.readLine()) {
115                 all.append(s);
116                 all.append("\r\n");
117                 if (s.length() == 0 || Character.isSpace(s.charAt(0))) {
118                     if (key == null) throw new Malformed("Message began with a blank line; no headers");
119                     ((CaseInsensitiveHash)headers).add(key, headers.get(key) + s);
120                     continue;
121                 }
122                 if (s.indexOf(':') == -1) throw new Malformed("Header line does not contain colon: " + s);
123                 key = s.substring(0, s.indexOf(':'));
124                 for(int i=0; i<key.length(); i++)
125                     if (key.charAt(i) < 33 || key.charAt(i) > 126)
126                         throw new Malformed("Header key \""+key+"\" contains invalid character \"" + key.charAt(i) + "\"");
127                 String val = s.substring(s.indexOf(':') + 1).trim();
128                 while(val.length() > 0 && Character.isSpace(val.charAt(0))) val = val.substring(1);
129                 if (key.startsWith("Resent-")) {
130                     if (key.startsWith("Resent-From")) resent.addElement(new Hashtable());
131                     ((Hashtable)resent.lastElement()).put(key.substring(7), val);
132                 } else if (key.startsWith("Return-Path")) {
133                     rs.pushback(s); traces.addElement(new Trace(rs));
134                 } else if (key.equals("X-org.ibex.mail.headers.envelopeFrom")) {
135                     if (envelopeFrom == null) envelopeFrom = new Address(val);
136                 } else if (key.equals("X-org.ibex.mail.headers.envelopeTo")) {
137                     if (envelopeTo == null) envelopeTo = new Address(val);
138                 } else {
139                     // just append it to the previous one; valid for Comments/Keywords
140                     if (headers.get(key) != null) val = headers.get(key) + " " + val;
141                     ((CaseInsensitiveHash)headers).add(key, val);
142                 }            
143             }
144
145             // FIXME what if all are null?
146             this.to           = headers.get("To") == null   ? envelopeTo    : new Address((String)headers.get("To"));
147             this.from         = headers.get("From") == null ? envelopeFrom  : new Address((String)headers.get("From"));
148             this.envelopeFrom = envelopeFrom == null        ? this.from     : envelopeFrom;
149             this.envelopeTo   = envelopeTo == null          ? this.to       : envelopeTo;
150
151             this.date      = new Date(); // FIXME (Date)headers.get("Date");
152             this.replyto   = headers.get("Reply-To") == null ? null : new Address((String)headers.get("Reply-To"));
153             this.subject   = (String)headers.get("Subject");
154             this.messageid = (String)headers.get("Message-Id");
155             if (headers.get("Cc") != null) {
156                 StringTokenizer st = new StringTokenizer((String)headers.get("Cc"));
157                 this.cc = new Address[st.countTokens()];
158                 for(int i=0; i<this.cc.length; i++) this.cc[i] = new Address(st.nextToken());
159             } else {
160                 this.cc = new Address[0];
161             }
162             if (headers.get("Bcc") != null) {
163                 StringTokenizer st = new StringTokenizer((String)headers.get("Bcc"));
164                 this.bcc = new Address[st.countTokens()];
165                 for(int i=0; i<this.bcc.length; i++) this.bcc[i] = new Address(st.nextToken());
166             } else {
167                 this.bcc = new Address[0];
168             }
169             resent.copyInto(this.resent = new Hashtable[resent.size()]);
170             traces.copyInto(this.traces = new Trace[traces.size()]);
171             allHeaders = all.toString();
172             StringBuffer body = new StringBuffer();
173             int lines = 0;
174             for(String s = rs.readLine();; s = rs.readLine()) { if (s == null) break; lines++; body.append(s + "\r\n"); }
175             this.lines = lines;
176             this.body = body.toString();
177         } catch (IOException e) { throw new MailException.IOException(e); }
178     }
179
180     // http://www.jwz.org/doc/mid.html
181     private static final Random random = new Random();
182     public static String generateFreshMessageId() {
183         StringBuffer ret = new StringBuffer();
184         ret.append('<');
185         ret.append(Base36.encode(System.currentTimeMillis()));
186         ret.append('.');
187         ret.append(Base36.encode(random.nextLong()));
188         ret.append('.');
189         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
190         ret.append('>');
191         return ret.toString();
192     }
193
194     public String rfc822() { return allHeaders + "\r\n" + body; }
195     public int rfc822size() { return allHeaders.length() + 2 /* CRLF */ + body.length(); }  // FIXME: double check this
196
197     public String summary() {
198         return
199             "          Subject: " + subject + "\n" +
200             "     EnvelopeFrom: " + envelopeFrom + "\n" +
201             "       EnvelopeTo: " + envelopeTo + "\n" +
202             "        MessageId: " + messageid;
203     }
204
205     //  use null-sender for error messages (don't send errors to the null addr)
206     public Message bounce(String reason) { throw new RuntimeException("bounce not implemented"); }  // FIXME!
207
208     private static class CaseInsensitiveHash extends Hashtable {
209         public Object get(Object o) { return (o instanceof String) ? super.get(((String)o).toLowerCase()) : super.get(o); }
210         public Object put(Object k, Object v) { throw new Error("you cannot write to a CaseInsensitiveHash"); }
211         void add(Object k, Object v) { if (k instanceof String) super.put(((String)k).toLowerCase(), v); else super.put(k, v); }
212     }
213
214 }