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