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