more bugfixes
[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("X-org.ibex.mail-envelopeFrom: " + envelopeFrom + "\r\n");
52         w.write("X-org.ibex.mail-envelopeTo: "); for(int i=0;i<envelopeTo.length;i++) w.write(envelopeTo[i]+" "); w.write("\r\n");
53         w.write(allHeaders);
54         w.write("\r\n");
55         w.write(body);
56         w.flush();
57     }
58
59     public class Trace {
60         final String returnPath;
61         final Element[] elements;
62         public Trace(LineReader lr) throws Trace.Malformed, IOException {
63             String retPath = lr.readLine();
64             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
65             returnPath = retPath.substring(12).trim();
66             Vec el = new Vec();
67             while(true) {
68                 String s = lr.readLine();
69                 if (s == null) break;
70                 if (!s.startsWith("Received:")) { lr.pushback(s); break; }
71                 s = s.substring(9).trim();
72                 el.addElement(new Element(s));
73             }
74             elements = new Element[el.size()];
75             el.copyInto(elements);
76         }
77         public class Element {
78              String fromDomain;
79              String fromIP;
80              String toDomain;
81              String forWhom;
82              Date date;
83             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
84                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
85             public Element(String s) throws Trace.Malformed {
86                 StringTokenizer st = new StringTokenizer(s);
87                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
88                 fromDomain = st.nextToken();
89                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
90                 toDomain = st.nextToken();
91                 // FIXME not done yet
92             }
93         }
94         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
95     }
96
97     public static class Malformed extends MailException.Malformed { public Malformed(String s) { super(s); } }
98
99     public Message(Address envelopeFrom, Address[] envelopeTo, String s, Date arrival)
100         { this(envelopeFrom, envelopeTo, new LineReader(new StringReader(s)), arrival); }
101     public Message(Address envelopeFrom, Address[] envelopeTo, LineReader rs) { this(envelopeFrom, envelopeTo, rs, null); }
102     public Message(Address envelopeFrom, Address[] envelopeTo, LineReader rs, Date arrival) {
103         try {
104             this.arrival = arrival == null ? new Date() : arrival;
105             this.headers = new CaseInsensitiveHash();
106             Vec envelopeToHeader = new Vec();
107             String key = null;
108             StringBuffer all = new StringBuffer();
109             Date date = null;
110             Address to = null, from = null, replyto = null;
111             String subject = null, messageid = null;
112             Vec cc = new Vec(), bcc = new Vec(), resent = new Vec(), traces = new Vec();
113             for(String s = rs.readLine(); s != null && !s.equals(""); s = rs.readLine()) {
114                 all.append(s);
115                 all.append("\r\n");
116                 if (s.length() == 0 || Character.isSpace(s.charAt(0))) {
117                     if (key == null) throw new Malformed("Message began with a blank line; no headers");
118                     ((CaseInsensitiveHash)headers).add(key, headers.get(key) + s);
119                     continue;
120                 }
121                 if (s.indexOf(':') == -1) throw new Malformed("Header line does not contain colon: " + s);
122                 key = s.substring(0, s.indexOf(':'));
123                 for(int i=0; i<key.length(); i++)
124                     if (key.charAt(i) < 33 || key.charAt(i) > 126)
125                         throw new Malformed("Header key \""+key+"\" contains invalid character \"" + key.charAt(i) + "\"");
126                 String val = s.substring(s.indexOf(':') + 1).trim();
127                 while(val.length() > 0 && Character.isSpace(val.charAt(0))) val = val.substring(1);
128                 if (key.startsWith("Resent-")) {
129                     if (key.startsWith("Resent-From")) resent.addElement(new Hashtable());
130                     ((Hashtable)resent.lastElement()).put(key.substring(7), val);
131                 } else if (key.startsWith("Return-Path")) {
132                     rs.pushback(s); traces.addElement(new Trace(rs));
133                 } else if (key.equals("X-org.ibex.mail.headers.envelopeFrom")) {
134                     if (envelopeFrom == null) envelopeFrom = new Address(val);
135                 } else if (key.equals("X-org.ibex.mail.headers.envelopeTo")) {
136                     if (envelopeTo == null) envelopeToHeader.addElement(new Address(val));
137                 } else {
138                     // just append it to the previous one; valid for Comments/Keywords
139                     if (headers.get(key) != null) val = headers.get(key) + " " + val;
140                     ((CaseInsensitiveHash)headers).add(key, val);
141                 }            
142             }
143             if (envelopeTo == null) envelopeTo = new Address[envelopeToHeader.size()];
144             envelopeToHeader.copyInto(envelopeTo);
145
146             // FIXME what if all are null?
147             this.to           = headers.get("To") == null   ? envelopeTo[0] : new Address((String)headers.get("To"));
148             this.from         = headers.get("From") == null ? envelopeFrom  : new Address((String)headers.get("From"));
149             this.envelopeFrom = envelopeFrom == null        ? this.from                 : envelopeFrom;
150             this.envelopeTo   = envelopeTo == null          ? new Address[] { this.to } : envelopeTo;
151
152             this.date      = new Date(); // FIXME (Date)headers.get("Date");
153             this.replyto   = headers.get("Reply-To") == null ? null : new Address((String)headers.get("Reply-To"));
154             this.subject   = (String)headers.get("Subject");
155             this.messageid = (String)headers.get("Message-Id");
156             if (headers.get("Cc") != null) {
157                 StringTokenizer st = new StringTokenizer((String)headers.get("Cc"));
158                 this.cc = new Address[st.countTokens()];
159                 for(int i=0; i<this.cc.length; i++) this.cc[i] = new Address(st.nextToken());
160             } else {
161                 this.cc = new Address[0];
162             }
163             if (headers.get("Bcc") != null) {
164                 StringTokenizer st = new StringTokenizer((String)headers.get("Bcc"));
165                 this.bcc = new Address[st.countTokens()];
166                 for(int i=0; i<this.bcc.length; i++) this.bcc[i] = new Address(st.nextToken());
167             } else {
168                 this.bcc = new Address[0];
169             }
170             resent.copyInto(this.resent = new Hashtable[resent.size()]);
171             traces.copyInto(this.traces = new Trace[traces.size()]);
172             allHeaders = all.toString();
173             StringBuffer body = new StringBuffer();
174             int lines = 0;
175             for(String s = rs.readLine();; s = rs.readLine()) { if (s == null) break; lines++; body.append(s + "\r\n"); }
176             this.lines = lines;
177             this.body = body.toString();
178         } catch (IOException e) { throw new MailException.IOException(e); }
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 rfc822() { return allHeaders + "\r\n" + body; }
196     public int rfc822size() { return allHeaders.length() + 2 /* CRLF */ + body.length(); }  // FIXME: double check this
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
209     private static class CaseInsensitiveHash extends Hashtable {
210         public Object get(Object o) { return (o instanceof String) ? super.get(((String)o).toLowerCase()) : super.get(o); }
211         public Object put(Object k, Object v) { throw new Error("you cannot write to a CaseInsensitiveHash"); }
212         void add(Object k, Object v) { if (k instanceof String) super.put(((String)k).toLowerCase(), v); else super.put(k, v); }
213     }
214
215 }