0406cf6c543373d44440eea9607eabb6e16886d0
[org.ibex.mail.git] / src / org / ibex / mail / Message.java
1 package org.ibex.mail;
2 import org.ibex.crypto.*;
3 import org.ibex.util.*;
4 import org.ibex.mail.protocol.*;
5 import org.ibex.io.*;
6 import org.ibex.net.*;
7 import java.util.*;
8 import java.net.*;
9 import java.io.*;
10
11 // FIXME this is important
12 // folded headers: can insert CRLF anywhere that whitespace appears (before the whitespace)
13
14 // soft line limit (suggested): 78 chars /  hard line limit: 998 chars
15 // date/time parsing: see spec, 3.3
16
17 // FIXME: messages must NEVER contain 8-bit binary data; this is a violation of IMAP
18
19 // FEATURE: PGP-signature-parsing
20 // FEATURE: mailing list header parsing
21 // FEATURE: delivery status notification (and the sneaky variety)
22 // FEATURE: threading as in http://www.jwz.org/doc/threading.html
23 // FEATURE: lazy body
24
25 /** 
26  *  [immutable] This class encapsulates a message "floating in the
27  *  ether": RFC2822 data but no storage-specific flags or other
28  *  metadata.
29  */
30 public class Message extends org.ibex.js.JSReflection {
31
32     public final String allHeaders;           // pristine headers
33     public final CaseInsensitiveHash headers; // hash of headers (not including resent's and traces)
34     public final String body;                 // entire body
35     public final int lines;                   // lines in the body
36
37     public final Date date;
38     public final Address to;
39     public final Address from;                // if multiple From entries, this is sender
40     public final Address replyto;             // if none provided, this is equal to sender
41     public final String subject;
42     public final String messageid;
43     public final Address[] cc;
44     public final Address[] bcc;
45     public final Hashtable[] resent;
46     public final Trace[] traces;
47
48     public final Address envelopeFrom;
49     public final Address envelopeTo;
50
51     public final Date arrival;         // when the message first arrived at this machine; IMAP "internal date message attr"
52     
53     public int size() { return allHeaders.length() + 2 /* CRLF */ + body.length(); }
54     public String toString() { return allHeaders + "\r\n" + body; }
55
56     public void dump(Stream s) {
57         s.setNewline("\r\n");
58         s.println("X-org.ibex.mail.headers.envelope.From: " + envelopeFrom);
59         s.println("X-org.ibex.mail.headers.envelope.To: " + envelopeTo);
60         s.println(allHeaders);
61         s.println();
62         s.println(body);
63         s.flush();
64     }
65
66     public class Trace {
67         final String returnPath;
68         final Element[] elements;
69         public Trace(Stream stream) throws Trace.Malformed {
70             String retPath = stream.readln();
71             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
72             returnPath = retPath.substring(12).trim();
73             Vec el = new Vec();
74             while(true) {
75                 String s = stream.readln();
76                 if (s == null) break;
77                 if (!s.startsWith("Received:")) { stream.unread(s); break; }
78                 s = s.substring(9).trim();
79                 el.addElement(new Element(s));
80             }
81             elements = new Element[el.size()];
82             el.copyInto(elements);
83         }
84         public class Element {
85              String fromDomain;
86              String fromIP;
87              String toDomain;
88              String forWhom;
89              Date date;
90             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
91                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
92             public Element(String s) throws Trace.Malformed {
93                 StringTokenizer st = new StringTokenizer(s);
94                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
95                 fromDomain = st.nextToken();
96                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
97                 toDomain = st.nextToken();
98                 // FIXME not done yet
99             }
100         }
101         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
102     }
103
104     public static class Malformed extends Exception { public Malformed(String s) { super(s); } }
105
106     public Message(Address from, Address to, String s, Date arrival) throws Malformed {this(from,to,new Stream(s), arrival); }
107     public Message(Address from, Address to, Stream in) throws Malformed { this(from, to, in, new Date()); }
108     public Message(Address envelopeFrom, Address envelopeTo, Stream stream, Date arrival) throws Malformed {
109         this.arrival = arrival;
110         this.headers = new CaseInsensitiveHash();
111         Vec envelopeToHeader = new Vec();
112         String key = null;
113         StringBuffer all = new StringBuffer();
114         Date date = null;
115         Address to = null, from = null, replyto = null;
116         String subject = null, messageid = null;
117         Vec cc = new Vec(), bcc = new Vec(), resent = new Vec(), traces = new Vec();
118         int lines = 0;
119         for(String s = stream.readln(); s != null && !s.equals(""); s = stream.readln()) {
120             all.append(s);
121             lines++;
122             all.append("\r\n");
123             if (s.length() == 0 || Character.isSpace(s.charAt(0))) {
124                 if (key == null) throw new Malformed("Message began with a blank line; no headers");
125                 ((CaseInsensitiveHash)headers).add(key, headers.get(key) + s);
126                 continue;
127             }
128             if (s.indexOf(':') == -1) throw new Malformed("Header line does not contain colon: " + s);
129             key = s.substring(0, s.indexOf(':'));
130             for(int i=0; i<key.length(); i++)
131                 if (key.charAt(i) < 33 || key.charAt(i) > 126)
132                     throw new Malformed("Header key \""+key+"\" contains invalid character \"" + key.charAt(i) + "\"");
133             String val = s.substring(s.indexOf(':') + 1).trim();
134             while(val.length() > 0 && Character.isSpace(val.charAt(0))) val = val.substring(1);
135             if (key.startsWith("Resent-")) {
136                 if (resent.size() == 0 || key.startsWith("Resent-From")) resent.addElement(new Hashtable());
137                 ((Hashtable)resent.lastElement()).put(key.substring(7), val);
138             } else if (key.startsWith("Return-Path")) {
139                 stream.unread(s); traces.addElement(new Trace(stream));
140             } else if (key.equals("X-org.ibex.mail.headers.envelope.From")) {
141                 try { if (envelopeFrom == null) envelopeFrom = new Address(val);
142                 } catch (Address.Malformed a) { Log.warn(this, a); }
143             } else if (key.equals("X-org.ibex.mail.headers.envelope.To")) {
144                 try {if (envelopeTo == null) envelopeTo = new Address(val);
145                 } catch (Address.Malformed a) { Log.warn(this, a); }
146             } else {
147                 // just append it to the previous one; valid for Comments/Keywords
148                 if (headers.get(key) != null) val = headers.get(key) + " " + val;
149                 ((CaseInsensitiveHash)headers).add(key, val);
150             }            
151         }
152         
153         // FIXME what if all are null?
154         this.to           = headers.get("To") == null   ? envelopeTo    : Address.parse((String)headers.get("To"));
155         this.from         = headers.get("From") == null ? envelopeFrom  : Address.parse((String)headers.get("From"));
156         this.envelopeFrom = envelopeFrom == null        ? this.from     : envelopeFrom;
157         this.envelopeTo   = envelopeTo == null          ? this.to       : envelopeTo;
158         
159         this.date      = new Date(); // FIXME (Date)headers.get("Date");
160         this.replyto   = headers.get("Reply-To") == null ? null : Address.parse((String)headers.get("Reply-To"));
161         this.subject   = (String)headers.get("Subject");
162         this.messageid = (String)headers.get("Message-Id");
163         if (headers.get("Cc") != null) {
164             // FIXME: tokenize better
165             StringTokenizer st = new StringTokenizer((String)headers.get("Cc"), ",");
166             this.cc = new Address[st.countTokens()];
167             for(int i=0; i<this.cc.length; i++) this.cc[i] = Address.parse(st.nextToken());
168         } else {
169             this.cc = new Address[0];
170         }
171         if (headers.get("Bcc") != null) {
172             StringTokenizer st = new StringTokenizer((String)headers.get("Bcc"));
173             this.bcc = new Address[st.countTokens()];
174             for(int i=0; i<this.bcc.length; i++) this.bcc[i] = Address.parse(st.nextToken());
175         } else {
176             this.bcc = new Address[0];
177         }
178         resent.copyInto(this.resent = new Hashtable[resent.size()]);
179         traces.copyInto(this.traces = new Trace[traces.size()]);
180         allHeaders = all.toString();
181         StringBuffer body = new StringBuffer();
182         for(String s = stream.readln();; s = stream.readln()) {
183             if (s == null) break;
184             lines++;
185             body.append(s);       // FIXME: we're assuming all mail messages fit in memory
186             body.append("\r\n");
187         }
188         this.lines = lines;
189         this.body = body.toString();
190     }
191     
192     // http://www.jwz.org/doc/mid.html
193     private static final Random random = new Random();
194     public static String generateFreshMessageId() {
195         StringBuffer ret = new StringBuffer();
196         ret.append('<');
197         ret.append(Base36.encode(System.currentTimeMillis()));
198         ret.append('.');
199         ret.append(Base36.encode(random.nextLong()));
200         ret.append('.');
201         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
202         ret.append('>');
203         return ret.toString();
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     public static class CaseInsensitiveHash extends org.ibex.js.JSReflection {
210         private Hashtable stuff = new Hashtable();
211         public Object get(Object o) { return stuff.get(((String)o).toLowerCase()); }
212         void add(Object k, Object v) { if (k instanceof String) stuff.put(((String)k).toLowerCase(), v); else stuff.put(k, v); }
213     }
214
215     public String summary() {
216         return
217             "          Subject: " + subject + "\n" +
218             "     EnvelopeFrom: " + envelopeFrom + "\n" +
219             "       EnvelopeTo: " + envelopeTo + "\n" +
220             "        MessageId: " + messageid;
221     }
222 }