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