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