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