restructuring; broke out Query, cleaned up Mailbox
[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     // FIXME make this immutable
30     private static class CaseInsensitiveHash extends Hashtable {
31         public Object get(Object o) {
32             if (o instanceof String) return super.get(((String)o).toLowerCase());
33             return super.get(o);
34         }
35         public Object put(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 static class Persistent {
75         public boolean deleted = false;
76         public boolean seen = false;
77         public boolean flagged = false;
78         public boolean draft = false;
79         public boolean answered = false;
80         public boolean recent = false;
81         public int uid = 0;
82     }
83     */
84         /*
85     public static class StoredMessage extends Message {
86         public int uid;
87         public final int uid;
88         public final int uidValidity;     // must be reset if mailbox is deleted and then recreated
89         public final int sequenceNumber;  // starts at 1; numbers reshuffled upon EXPUNGE
90         public Hash keywords = new Hash();  
91         public boolean deleted = false;
92         public boolean seen = false;
93         public boolean flagged = false;
94         public boolean draft = false;
95         public boolean answered = false;
96         public boolean recent = false;    // "Message is "recently" arrived in this mailbox.  This
97                                           // session is the first session to have been notified
98                                           // about this message;
99         public StoredMessage(LineReader rs) throws IOException, MailException.Malformed { super(rs); }
100     }
101         */
102
103     public class Trace {
104         final String returnPath;
105         final Element[] elements;
106         public Trace(LineReader lr) throws Trace.Malformed, IOException {
107             String retPath = lr.readLine();
108             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
109             returnPath = retPath.substring(12).trim();
110             Vec el = new Vec();
111             while(true) {
112                 String s = lr.readLine();
113                 if (s == null) break;
114                 if (!s.startsWith("Received:")) { lr.pushback(s); break; }
115                 s = s.substring(9).trim();
116                 el.addElement(new Element(s));
117             }
118             elements = new Element[el.size()];
119             el.copyInto(elements);
120         }
121         public class Element {
122              String fromDomain;
123              String fromIP;
124              String toDomain;
125              String forWhom;
126              Date date;
127             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
128                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
129             public Element(String s) throws Trace.Malformed {
130                 StringTokenizer st = new StringTokenizer(s);
131                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
132                 fromDomain = st.nextToken();
133                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
134                 toDomain = st.nextToken();
135                 // FIXME not done yet
136             }
137         }
138         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
139     }
140
141     public static class Malformed extends MailException.Malformed { public Malformed(String s) { super(s); } }
142     public Message(Address envelopeFrom, Address[] envelopeTo, LineReader rs) throws IOException, MailException.Malformed {
143         this.envelopeFrom = envelopeFrom;
144         this.envelopeTo = envelopeTo;
145         this.arrival = new Date();
146         this.headers = new CaseInsensitiveHash();
147         String key = null;
148         StringBuffer all = new StringBuffer();
149         Date date = null;
150         Address to = null, from = null, replyto = null;
151         String subject = null, messageid = null;
152         Vec cc = new Vec(), bcc = new Vec(), resent = new Vec(), traces = new Vec();
153         for(String s = rs.readLine(); s != null && !s.equals(""); s = rs.readLine()) {
154             all.append(s);
155             all.append("\r\n");
156             if (s.length() == 0 || Character.isSpace(s.charAt(0))) {
157                 if (key == null) throw new Malformed("Message began with a blank line; no headers");
158                 headers.put(key, headers.get(key) + s);
159                 continue;
160             }
161             if (s.indexOf(':') == -1) throw new Malformed("Header line does not contain colon: " + s);
162             key = s.substring(0, s.indexOf(':'));
163             for(int i=0; i<key.length(); i++)
164                 if (key.charAt(i) < 33 || key.charAt(i) > 126)
165                     throw new Malformed("Header key \""+key+"\" contains invalid character \"" + key.charAt(i) + "\"");
166             String val = s.substring(s.indexOf(':') + 1).trim();
167             while(Character.isSpace(val.charAt(0))) val = val.substring(1);
168             if (key.startsWith("Resent-")) {
169                 if (key.startsWith("Resent-From")) resent.addElement(new Hashtable());
170                 ((Hashtable)resent.lastElement()).put(key.substring(7), val);
171             } else if (key.startsWith("Return-Path:")) {
172                 rs.pushback(s); traces.addElement(new Trace(rs));
173             } else {
174                 // just append it to the previous one; valid for Comments/Keywords
175                 if (headers.get(key) != null) val = headers.get(key) + " " + val;
176                 headers.put(key, val);
177             }            
178         }
179
180         this.date      = (Date)headers.get("Date");
181         this.to        = new Address((String)headers.get("To"));  // FIXME what if null?
182         this.from      = headers.get("From") == null     ? envelopeFrom : new Address((String)headers.get("From"));
183         this.replyto   = headers.get("Reply-To") == null ? null : new Address((String)headers.get("Reply-To"));
184         this.subject   = (String)headers.get("Subject");
185         this.messageid = (String)headers.get("Message-Id");
186         if (headers.get("Cc") != null) {
187             StringTokenizer st = new StringTokenizer((String)headers.get("Cc"));
188             this.cc = new Address[st.countTokens()];
189             for(int i=0; i<this.cc.length; i++) this.cc[i] = new Address(st.nextToken());
190         } else {
191             this.cc = new Address[0];
192         }
193         if (headers.get("Bcc") != null) {
194             StringTokenizer st = new StringTokenizer((String)headers.get("Bcc"));
195             this.bcc = new Address[st.countTokens()];
196             for(int i=0; i<this.bcc.length; i++) this.bcc[i] = new Address(st.nextToken());
197         } else {
198             this.bcc = new Address[0];
199         }
200         resent.copyInto(this.resent = new Hashtable[resent.size()]);
201         traces.copyInto(this.traces = new Trace[traces.size()]);
202         allHeaders = all.toString();
203         StringBuffer body = new StringBuffer();
204         int lines = 0;
205         for(String s = rs.readLine();; s = rs.readLine()) { if (s == null) break; lines++; body.append(s + "\r\n"); }
206         this.lines = lines;
207         this.body = body.toString();
208     }
209
210     // http://www.jwz.org/doc/mid.html
211     private static final Random random = new Random();
212     public static String generateFreshMessageId() {
213         StringBuffer ret = new StringBuffer();
214         ret.append('<');
215         ret.append(Base36.encode(System.currentTimeMillis()));
216         ret.append('.');
217         ret.append(Base36.encode(random.nextLong()));
218         ret.append('.');
219         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
220         ret.append('>');
221         return ret.toString();
222     }
223
224     public String summary() {
225         return
226             "          Subject: " + subject + "\n" +
227             "     EnvelopeFrom: " + envelopeFrom + "\n" +
228             "       EnvelopeTo: " + envelopeTo + "\n" +
229             "        MessageId: " + messageid;
230     }
231
232     public Message bounce(String reason) {
233         //  use null-sender for error messages (don't send errors to the null addr)
234         // FIXME
235         throw new RuntimeException("bounce not implemented");
236     }
237 }