formatting fix
[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 // FIXME this is important
11 // folded headers: can insert CRLF anywhere that whitespace appears (before the whitespace)
12
13 // soft line limit (suggested): 78 chars /  hard line limit: 998 chars
14 // date/time parsing: see spec, 3.3
15
16 // FIXME: messages must NEVER contain 8-bit binary data; this is a violation of IMAP
17
18 // FEATURE: PGP-signature-parsing
19 // FEATURE: mailing list header parsing
20 // FEATURE: delivery status notification (and the sneaky variety)
21 // FEATURE: threading as in http://www.jwz.org/doc/threading.html
22 // FEATURE: lazy body
23
24 /** 
25  *  [immutable] This class encapsulates a message "floating in the
26  *  ether": RFC2822 data but no storage-specific flags or other
27  *  metadata.
28  */
29 public class Message extends JSReflection {
30
31     public final String allHeaders;           // pristine headers
32     public final Hashtable headers;           // hash of headers (not including resent's and traces)
33     public final String body;                 // entire body
34     public final int lines;                   // lines in the body
35
36     public final Date date;
37     public final Address to;
38     public final Address from;                // if multiple From entries, this is sender
39     public final Address replyto;             // if none provided, this is equal to sender
40     public final String subject;
41     public final String messageid;
42     public final Address[] cc;
43     public final Address[] bcc;
44     public final Hashtable[] resent;
45     public final Trace[] traces;
46
47     public final Address envelopeFrom;
48     public final Address envelopeTo;
49
50     public final Date arrival;         // when the message first arrived at this machine; IMAP "internal date message attr"
51     
52     public void dump(OutputStream os) throws IOException {
53         Writer w = new OutputStreamWriter(os);
54         w.write("X-org.ibex.mail-envelopeFrom: " + envelopeFrom + "\r\n");
55         w.write("X-org.ibex.mail-envelopeTo: " + envelopeTo + "\r\n");
56         w.write(allHeaders);
57         w.write("\r\n");
58         w.write(body);
59         w.flush();
60     }
61
62     public class Trace {
63         final String returnPath;
64         final Element[] elements;
65         public Trace(LineReader lr) throws Trace.Malformed, IOException {
66             String retPath = lr.readLine();
67             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
68             returnPath = retPath.substring(12).trim();
69             Vec el = new Vec();
70             while(true) {
71                 String s = lr.readLine();
72                 if (s == null) break;
73                 if (!s.startsWith("Received:")) { lr.pushback(s); break; }
74                 s = s.substring(9).trim();
75                 el.addElement(new Element(s));
76             }
77             elements = new Element[el.size()];
78             el.copyInto(elements);
79         }
80         public class Element {
81              String fromDomain;
82              String fromIP;
83              String toDomain;
84              String forWhom;
85              Date date;
86             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
87                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
88             public Element(String s) throws Trace.Malformed {
89                 StringTokenizer st = new StringTokenizer(s);
90                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
91                 fromDomain = st.nextToken();
92                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
93                 toDomain = st.nextToken();
94                 // FIXME not done yet
95             }
96         }
97         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
98     }
99
100     public static class Malformed extends MailException.Malformed { public Malformed(String s) { super(s); } }
101
102     public Message(Address envelopeFrom, Address envelopeTo, String s, Date arrival)
103         { this(envelopeFrom, envelopeTo, new LineReader(new StringReader(s)), arrival); }
104     public Message(Address envelopeFrom, Address envelopeTo, LineReader rs) { this(envelopeFrom, envelopeTo, rs, null); }
105     public Message(Address envelopeFrom, Address envelopeTo, LineReader rs, Date arrival) {
106         try {
107             this.arrival = arrival == null ? new Date() : arrival;
108             this.headers = new CaseInsensitiveHash();
109             Vec envelopeToHeader = new Vec();
110             String key = null;
111             StringBuffer all = new StringBuffer();
112             Date date = null;
113             Address to = null, from = null, replyto = null;
114             String subject = null, messageid = null;
115             Vec cc = new Vec(), bcc = new Vec(), resent = new Vec(), traces = new Vec();
116             for(String s = rs.readLine(); s != null && !s.equals(""); s = rs.readLine()) {
117                 all.append(s);
118                 all.append("\r\n");
119                 if (s.length() == 0 || Character.isSpace(s.charAt(0))) {
120                     if (key == null) throw new Malformed("Message began with a blank line; no headers");
121                     ((CaseInsensitiveHash)headers).add(key, headers.get(key) + s);
122                     continue;
123                 }
124                 if (s.indexOf(':') == -1) throw new Malformed("Header line does not contain colon: " + s);
125                 key = s.substring(0, s.indexOf(':'));
126                 for(int i=0; i<key.length(); i++)
127                     if (key.charAt(i) < 33 || key.charAt(i) > 126)
128                         throw new Malformed("Header key \""+key+"\" contains invalid character \"" + key.charAt(i) + "\"");
129                 String val = s.substring(s.indexOf(':') + 1).trim();
130                 while(val.length() > 0 && Character.isSpace(val.charAt(0))) val = val.substring(1);
131                 if (key.startsWith("Resent-")) {
132                     if (key.startsWith("Resent-From")) resent.addElement(new Hashtable());
133                     ((Hashtable)resent.lastElement()).put(key.substring(7), val);
134                 } else if (key.startsWith("Return-Path")) {
135                     rs.pushback(s); traces.addElement(new Trace(rs));
136                 } else if (key.equals("X-org.ibex.mail.headers.envelopeFrom")) {
137                     if (envelopeFrom == null) envelopeFrom = new Address(val);
138                 } else if (key.equals("X-org.ibex.mail.headers.envelopeTo")) {
139                     if (envelopeTo == null) envelopeTo = new Address(val);
140                 } else {
141                     // just append it to the previous one; valid for Comments/Keywords
142                     if (headers.get(key) != null) val = headers.get(key) + " " + val;
143                     ((CaseInsensitiveHash)headers).add(key, val);
144                 }            
145             }
146
147             // FIXME what if all are null?
148             this.to           = headers.get("To") == null   ? envelopeTo    : new Address((String)headers.get("To"));
149             this.from         = headers.get("From") == null ? envelopeFrom  : new Address((String)headers.get("From"));
150             this.envelopeFrom = envelopeFrom == null        ? this.from     : envelopeFrom;
151             this.envelopeTo   = envelopeTo == null          ? this.to       : envelopeTo;
152
153             this.date      = new Date(); // FIXME (Date)headers.get("Date");
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         } catch (IOException e) { throw new MailException.IOException(e); }
180     }
181
182     // http://www.jwz.org/doc/mid.html
183     private static final Random random = new Random();
184     public static String generateFreshMessageId() {
185         StringBuffer ret = new StringBuffer();
186         ret.append('<');
187         ret.append(Base36.encode(System.currentTimeMillis()));
188         ret.append('.');
189         ret.append(Base36.encode(random.nextLong()));
190         ret.append('.');
191         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
192         ret.append('>');
193         return ret.toString();
194     }
195
196     public String rfc822() { return allHeaders + "\r\n" + body; }
197     public int rfc822size() { return allHeaders.length() + 2 /* CRLF */ + body.length(); }  // FIXME: double check this
198
199     public String summary() {
200         return
201             "          Subject: " + subject + "\n" +
202             "     EnvelopeFrom: " + envelopeFrom + "\n" +
203             "       EnvelopeTo: " + envelopeTo + "\n" +
204             "        MessageId: " + messageid;
205     }
206
207     //  use null-sender for error messages (don't send errors to the null addr)
208     public Message bounce(String reason) { throw new RuntimeException("bounce not implemented"); }  // FIXME!
209
210     private static class CaseInsensitiveHash extends Hashtable {
211         public Object get(Object o) { return (o instanceof String) ? super.get(((String)o).toLowerCase()) : super.get(o); }
212         public Object put(Object k, Object v) { throw new Error("you cannot write to a CaseInsensitiveHash"); }
213         void add(Object k, Object v) { if (k instanceof String) super.put(((String)k).toLowerCase(), v); else super.put(k, v); }
214     }
215
216 }