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