8303ea8893a1c5acaa63ebb1d7702de764a00f0c
[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 // NOTE: always use Win32 line endings
11 // hard line limit: 998 chars
12 // soft line limit (suggested): 78 chars
13 // header fields: ascii 33-126 (but no colon)
14 // field body: anything ASCII except CRLF
15 // folded headers: can insert CRLF anywhere that whitespace appears (before the whitespace)
16 // body needs CRLF; one or the other alone is not acceptable
17 // date/time parsing: see 3.3
18
19 // FEATURE: MIME RFC2045, 2046, 2049
20 // FEATURE: PGP-signature-parsing
21 // FEATURE: mailing list header parsing
22 // FEATURE: delivery status notification (and the sneaky variety)
23 // FEATURE: threading as in http://www.jwz.org/doc/threading.html
24
25 public class Message extends JSReflection {
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 Trace[] traces;
41
42     public final Address envelopeFrom;
43     public final Address[] envelopeTo;
44
45     public void dump(OutputStream os) throws IOException {
46         Writer w = new OutputStreamWriter(os);
47         w.write(allHeaders);
48         w.write("\r\n");
49         w.write(body);
50         w.flush();
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     public class Trace {
62         final String returnPath;
63         final Element[] elements;
64         public Trace(LineReader lr) throws Trace.Malformed, IOException {
65             String retPath = lr.readLine();
66             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
67             returnPath = retPath.substring(12).trim();
68             Vec el = new Vec();
69             while(true) {
70                 String s = lr.readLine();
71                 if (s == null) break;
72                 if (!s.startsWith("Received:")) { lr.pushback(s); break; }
73                 s = s.substring(9).trim();
74                 el.addElement(new Element(s));
75             }
76             elements = new Element[el.size()];
77             el.copyInto(elements);
78         }
79         public class Element {
80              String fromDomain;
81              String fromIP;
82              String toDomain;
83              String forWhom;
84              Date date;
85             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
86                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
87             public Element(String s) throws Trace.Malformed {
88                 StringTokenizer st = new StringTokenizer(s);
89                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
90                 fromDomain = st.nextToken();
91                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
92                 toDomain = st.nextToken();
93                 // FIXME not done yet
94             }
95         }
96         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
97     }
98
99     public static class Malformed extends MailException.Malformed { public Malformed(String s) { super(s); } }
100     public Message(LineReader rs) throws IOException, Malformed {
101         String key = null;
102         StringBuffer all = new StringBuffer();
103         replyto = null;
104         subject = null;
105         messageid = null;
106         cc = null;
107         bcc = null;
108         resent = null;
109         traces = null;
110         envelopeFrom = null;
111         envelopeTo = null;
112
113         headers = new Hashtable();
114         date = null; // FIXME
115         to = null;
116         from = null;
117         for(String s = rs.readLine(); s != null && !s.equals(""); s = rs.readLine()) {
118             all.append(s);
119             all.append("\r\n");
120             if (s.length() == 0 || Character.isSpace(s.charAt(0))) {
121                 if (key == null) throw new Malformed("Message began with a blank line; no headers");
122                 headers.put(key, headers.get(key) + s);
123                 continue;
124             }
125             if (s.indexOf(':') == -1) throw new Malformed("Header line does not contain colon: " + s);
126             key = s.substring(0, s.indexOf(':'));
127             String val = s.substring(0, s.indexOf(':') + 1);
128             while(Character.isSpace(val.charAt(0))) val = val.substring(1);
129
130             if (headers.get(key) != null)
131                 if (key.startsWith("Resent-")) {
132                     // FIXME: multi-resent headers
133
134                 } else if (key.startsWith("Return-Path:")) {
135                     rs.pushback(s);
136                     Trace t = new Trace(rs);
137                     Trace[] newTraces = new Trace[traces == null ? 1 : traces.length + 1];
138                     if (traces != null) System.arraycopy(traces, 0, newTraces, 0, traces.length);
139                     traces = newTraces;
140                     traces[traces.length-1] = t;
141
142                 } else {
143                     // just append it to the previous one; valid for Comments/Keywords
144                     val = headers.get(key) + " " + val;
145                 } 
146             
147             headers.put(key, val);
148         }
149
150         allHeaders = all.toString();
151         StringBuffer body = new StringBuffer();
152         for(String s = rs.readLine();; s = rs.readLine()) { if (s == null) break; else body.append(s + "\r\n"); }
153         this.body = body.toString();
154     }
155
156     // http://www.jwz.org/doc/mid.html
157     public static String generateFreshMessageId() {
158         StringBuffer ret = new StringBuffer();
159         ret.append('<');
160         ret.append(Base36.encode(System.currentTimeMillis()));
161         ret.append('.');
162         ret.append(Base36.encode(random.nextLong()));
163         ret.append('.');
164         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
165         ret.append('>');
166         return ret.toString();
167     }
168
169     private static final Random random = new Random();
170 }