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