checkpoint imap support
[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     public final String allHeaders;   // pristine headers
23     public final Hashtable headers;   // hash of headers (not including resent's and traces)
24     public final String body;         // entire body
25
26     public final Date date;
27     public final Address to;
28     public final Address from;        // if multiple From entries, this is sender
29     public final Address replyto;     // if none provided, this is equal to sender
30     public final String subject;
31     public final String messageid;
32     public final Address[] cc;
33     public final Address[] bcc;
34     public final Hashtable[] resent;
35     public final Trace[] traces;
36
37     public final Address envelopeFrom;
38     public final Address[] envelopeTo;
39
40     public final Date arrival;         // when the message first arrived at this machine; IMAP "internal date message attr"
41     
42     public void dump(OutputStream os) throws IOException {
43         Writer w = new OutputStreamWriter(os);
44         w.write(allHeaders);
45         w.write("X-IbexMail-EnvelopeFrom: " + envelopeFrom + "\r\n");
46         w.write("X-IbexMail-EnvelopeTo: "); for(int i=0; i<envelopeTo.length; i++) w.write(envelopeTo[i] + " "); w.write("\r\n");
47         w.write("\r\n");
48         w.write(body);
49         w.flush();
50     }
51
52         /*
53     public static class StoredMessage extends Message {
54         public int uid;
55         public final int uid;
56         public final int uidValidity;     // must be reset if mailbox is deleted and then recreated
57         public final int sequenceNumber;  // starts at 1; numbers reshuffled upon EXPUNGE
58         public Hash keywords = new Hash();  
59         public boolean deleted = false;
60         public boolean seen = false;
61         public boolean flagged = false;
62         public boolean draft = false;
63         public boolean answered = false;
64         public boolean recent = false;    // "Message is "recently" arrived in this mailbox.  This
65                                           // session is the first session to have been notified
66                                           // about this message;
67         public StoredMessage(LineReader rs) throws IOException, MailException.Malformed { super(rs); }
68     }
69         */
70
71     public class Trace {
72         final String returnPath;
73         final Element[] elements;
74         public Trace(LineReader lr) throws Trace.Malformed, IOException {
75             String retPath = lr.readLine();
76             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
77             returnPath = retPath.substring(12).trim();
78             Vec el = new Vec();
79             while(true) {
80                 String s = lr.readLine();
81                 if (s == null) break;
82                 if (!s.startsWith("Received:")) { lr.pushback(s); break; }
83                 s = s.substring(9).trim();
84                 el.addElement(new Element(s));
85             }
86             elements = new Element[el.size()];
87             el.copyInto(elements);
88         }
89         public class Element {
90              String fromDomain;
91              String fromIP;
92              String toDomain;
93              String forWhom;
94              Date date;
95             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
96                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
97             public Element(String s) throws Trace.Malformed {
98                 StringTokenizer st = new StringTokenizer(s);
99                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
100                 fromDomain = st.nextToken();
101                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
102                 toDomain = st.nextToken();
103                 // FIXME not done yet
104             }
105         }
106         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
107     }
108
109     public static class Malformed extends MailException.Malformed { public Malformed(String s) { super(s); } }
110     public Message(Address envelopeFrom, Address[] envelopeTo, LineReader rs) throws IOException, MailException.Malformed {
111         this.envelopeFrom = envelopeFrom;
112         this.envelopeTo = envelopeTo;
113         this.arrival = new Date();
114         this.headers = new Hashtable();
115         String key = null;
116         StringBuffer all = new StringBuffer();
117         Date date = null;
118         Address to = null, from = null, replyto = null;
119         String subject = null, messageid = null;
120         Vec cc = new Vec(), bcc = new Vec(), resent = new Vec(), traces = new Vec();
121         for(String s = rs.readLine(); s != null && !s.equals(""); s = rs.readLine()) {
122             all.append(s);
123             all.append("\r\n");
124             if (s.length() == 0 || Character.isSpace(s.charAt(0))) {
125                 if (key == null) throw new Malformed("Message began with a blank line; no headers");
126                 headers.put(key, headers.get(key) + s);
127                 continue;
128             }
129             if (s.indexOf(':') == -1) throw new Malformed("Header line does not contain colon: " + s);
130             key = s.substring(0, s.indexOf(':'));
131             for(int i=0; i<key.length(); i++)
132                 if (key.charAt(i) < 33 || key.charAt(i) > 126)
133                     throw new Malformed("Header key \""+key+"\" contains invalid character \"" + key.charAt(i) + "\"");
134             String val = s.substring(s.indexOf(':') + 1).trim();
135             while(Character.isSpace(val.charAt(0))) val = val.substring(1);
136             if (key.startsWith("Resent-")) {
137                 if (key.startsWith("Resent-From")) resent.addElement(new Hashtable());
138                 ((Hashtable)resent.lastElement()).put(key.substring(7), val);
139             } else if (key.startsWith("Return-Path:")) {
140                 rs.pushback(s); traces.addElement(new Trace(rs));
141             } else {
142                 // just append it to the previous one; valid for Comments/Keywords
143                 if (headers.get(key) != null) val = headers.get(key) + " " + val;
144                 headers.put(key, val);
145             }            
146         }
147
148         this.date      = (Date)headers.get("Date");
149         this.to        = new Address((String)headers.get("To"));  // FIXME what if null?
150         this.from      = headers.get("From") == null     ? envelopeFrom : new Address((String)headers.get("From"));
151         this.replyto   = headers.get("Reply-To") == null ? null : new Address((String)headers.get("Reply-To"));
152         this.subject   = (String)headers.get("Subject");
153         this.messageid = (String)headers.get("Message-Id");
154         if (headers.get("Cc") != null) {
155             StringTokenizer st = new StringTokenizer((String)headers.get("Cc"));
156             this.cc = new Address[st.countTokens()];
157             for(int i=0; i<this.cc.length; i++) this.cc[i] = new Address(st.nextToken());
158         } else {
159             this.cc = new Address[0];
160         }
161         if (headers.get("Bcc") != null) {
162             StringTokenizer st = new StringTokenizer((String)headers.get("Bcc"));
163             this.bcc = new Address[st.countTokens()];
164             for(int i=0; i<this.bcc.length; i++) this.bcc[i] = new Address(st.nextToken());
165         } else {
166             this.bcc = new Address[0];
167         }
168         resent.copyInto(this.resent = new Hashtable[resent.size()]);
169         traces.copyInto(this.traces = new Trace[traces.size()]);
170         allHeaders = all.toString();
171         StringBuffer body = new StringBuffer();
172         for(String s = rs.readLine();; s = rs.readLine()) { if (s == null) break; else body.append(s + "\r\n"); }
173         this.body = body.toString();
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 String summary() {
191         return
192             "          Subject: " + subject + "\n" +
193             "     EnvelopeFrom: " + envelopeFrom + "\n" +
194             "       EnvelopeTo: " + envelopeTo + "\n" +
195             "        MessageId: " + messageid;
196     }
197
198     public Message bounce(String reason) {
199         //  use null-sender for error messages (don't send errors to the null addr)
200         // FIXME
201         throw new RuntimeException("bounce not implemented");
202     }
203 }