mail overhaul
[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     public void dump(Stream s) {
56         s.out.setNewline("\r\n");
57         s.out.println("X-org.ibex.mail.headers.envelope.From: " + envelopeFrom);
58         s.out.println("X-org.ibex.mail.headers.envelope.To: " + envelopeTo);
59         s.out.println(allHeaders);
60         s.out.println();
61         s.out.println(body);
62         s.out.flush();
63     }
64
65     public class Trace {
66         final String returnPath;
67         final Element[] elements;
68         public Trace(Stream stream) throws Trace.Malformed {
69             String retPath = stream.in.readln();
70             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
71             returnPath = retPath.substring(12).trim();
72             Vec el = new Vec();
73             while(true) {
74                 String s = stream.in.readln();
75                 if (s == null) break;
76                 if (!s.startsWith("Received:")) { stream.in.unread(s); break; }
77                 s = s.substring(9).trim();
78                 el.addElement(new Element(s));
79             }
80             elements = new Element[el.size()];
81             el.copyInto(elements);
82         }
83         public class Element {
84              String fromDomain;
85              String fromIP;
86              String toDomain;
87              String forWhom;
88              Date date;
89             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
90                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
91             public Element(String s) throws Trace.Malformed {
92                 StringTokenizer st = new StringTokenizer(s);
93                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
94                 fromDomain = st.nextToken();
95                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
96                 toDomain = st.nextToken();
97                 // FIXME not done yet
98             }
99         }
100         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
101     }
102
103     public static class Malformed extends RuntimeException { public Malformed(String s) { super(s); } }
104
105     public Message(Address from, Address to, String s, Date arrival) { this(from, to, new Stream(s), arrival); }
106     public Message(Address from, Address to, Stream in) { this(from, to, in, new Date()); }
107     public Message(Address envelopeFrom, Address envelopeTo, Stream stream, Date arrival) {
108         this.arrival = arrival;
109         this.headers = new CaseInsensitiveHash();
110         Vec envelopeToHeader = new Vec();
111         String key = null;
112         StringBuffer all = new StringBuffer();
113         Date date = null;
114         Address to = null, from = null, replyto = null;
115         String subject = null, messageid = null;
116         Vec cc = new Vec(), bcc = new Vec(), resent = new Vec(), traces = new Vec();
117         int lines = 0;
118         for(String s = stream.in.readln(); s != null && !s.equals(""); s = stream.in.readln()) {
119             all.append(s);
120             lines++;
121             all.append("\r\n");
122             if (s.length() == 0 || Character.isSpace(s.charAt(0))) {
123                 if (key == null) throw new Malformed("Message began with a blank line; no headers");
124                 ((CaseInsensitiveHash)headers).add(key, headers.get(key) + s);
125                 continue;
126             }
127             if (s.indexOf(':') == -1) throw new Malformed("Header line does not contain colon: " + s);
128             key = s.substring(0, s.indexOf(':'));
129             for(int i=0; i<key.length(); i++)
130                 if (key.charAt(i) < 33 || key.charAt(i) > 126)
131                     throw new Malformed("Header key \""+key+"\" contains invalid character \"" + key.charAt(i) + "\"");
132             String val = s.substring(s.indexOf(':') + 1).trim();
133             while(val.length() > 0 && Character.isSpace(val.charAt(0))) val = val.substring(1);
134             if (key.startsWith("Resent-")) {
135                 if (resent.size() == 0 || key.startsWith("Resent-From")) resent.addElement(new Hashtable());
136                 ((Hashtable)resent.lastElement()).put(key.substring(7), val);
137             } else if (key.startsWith("Return-Path")) {
138                 stream.in.unread(s); traces.addElement(new Trace(stream));
139             } else if (key.equals("X-org.ibex.mail.headers.envelope.From")) {
140                 if (envelopeFrom == null) envelopeFrom = new Address(val);
141             } else if (key.equals("X-org.ibex.mail.headers.envelope.To")) {
142                 if (envelopeTo == null) envelopeTo = new Address(val);
143             } else {
144                 // just append it to the previous one; valid for Comments/Keywords
145                 if (headers.get(key) != null) val = headers.get(key) + " " + val;
146                 ((CaseInsensitiveHash)headers).add(key, val);
147             }            
148         }
149         
150         // FIXME what if all are null?
151         this.to           = headers.get("To") == null   ? envelopeTo    : new Address((String)headers.get("To"));
152         this.from         = headers.get("From") == null ? envelopeFrom  : new Address((String)headers.get("From"));
153         this.envelopeFrom = envelopeFrom == null        ? this.from     : envelopeFrom;
154         this.envelopeTo   = envelopeTo == null          ? this.to       : envelopeTo;
155         
156         this.date      = new Date(); // FIXME (Date)headers.get("Date");
157         this.replyto   = headers.get("Reply-To") == null ? null : new Address((String)headers.get("Reply-To"));
158         this.subject   = (String)headers.get("Subject");
159         this.messageid = (String)headers.get("Message-Id");
160         if (headers.get("Cc") != null) {
161             // FIXME: tokenize better
162             StringTokenizer st = new StringTokenizer((String)headers.get("Cc"));
163             this.cc = new Address[st.countTokens()];
164             for(int i=0; i<this.cc.length; i++) this.cc[i] = new Address(st.nextToken());
165         } else {
166             this.cc = new Address[0];
167         }
168         if (headers.get("Bcc") != null) {
169             StringTokenizer st = new StringTokenizer((String)headers.get("Bcc"));
170             this.bcc = new Address[st.countTokens()];
171             for(int i=0; i<this.bcc.length; i++) this.bcc[i] = new Address(st.nextToken());
172         } else {
173             this.bcc = new Address[0];
174         }
175         resent.copyInto(this.resent = new Hashtable[resent.size()]);
176         traces.copyInto(this.traces = new Trace[traces.size()]);
177         allHeaders = all.toString();
178         StringBuffer body = new StringBuffer();
179         for(String s = stream.in.readln();; s = stream.in.readln()) {
180             if (s == null) break;
181             lines++;
182             body.append(s);       // FIXME: we're assuming all mail messages fit in memory
183             body.append("\r\n");
184         }
185         this.lines = lines;
186         this.body = body.toString();
187     }
188     
189     // http://www.jwz.org/doc/mid.html
190     private static final Random random = new Random();
191     public static String generateFreshMessageId() {
192         StringBuffer ret = new StringBuffer();
193         ret.append('<');
194         ret.append(Base36.encode(System.currentTimeMillis()));
195         ret.append('.');
196         ret.append(Base36.encode(random.nextLong()));
197         ret.append('.');
198         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
199         ret.append('>');
200         return ret.toString();
201     }
202
203     //  use null-sender for error messages (don't send errors to the null addr)
204     public Message bounce(String reason) { throw new RuntimeException("bounce not implemented"); }  // FIXME!
205  
206     public static class CaseInsensitiveHash extends org.ibex.js.JSReflection {
207         private Hashtable stuff = new Hashtable();
208         public Object get(Object o) { return stuff.get(((String)o).toLowerCase()); }
209         void add(Object k, Object v) { if (k instanceof String) stuff.put(((String)k).toLowerCase(), v); else stuff.put(k, v); }
210     }
211
212     public String summary() {
213         return
214             "          Subject: " + subject + "\n" +
215             "     EnvelopeFrom: " + envelopeFrom + "\n" +
216             "       EnvelopeTo: " + envelopeTo + "\n" +
217             "        MessageId: " + messageid;
218     }
219 }