total overhaul; were using MIME and MIME.Part now
[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 java.util.*;
7 import java.net.*;
8 import java.io.*;
9
10 // FIXME this is important: folded headers: can insert CRLF anywhere that whitespace appears (before the whitespace)
11
12 // soft line limit (suggested): 78 chars /  hard line limit: 998 chars
13 // date/time parsing: see spec, 3.3
14
15 // FIXME: messages must NEVER contain 8-bit binary data; this is a violation of IMAP
16
17 // FEATURE: PGP-signature-parsing
18 // FEATURE: mailing list header parsing
19 // FEATURE: delivery status notification (and the sneaky variety)
20 // FEATURE: threading as in http://www.jwz.org/doc/threading.html
21 // FEATURE: lazy body
22 // FIXME RFC822 1,000-char limit per line
23
24 /** 
25  *  [immutable] This class encapsulates a message "floating in the
26  *  ether": RFC2822 data but no storage-specific flags or other
27  *  metadata.
28  */
29 public class Message extends MIME.Part {
30
31     // Envelope //////////////////////////////////////////////////////////////////////////////
32
33     public final Envelope    envelope;
34     public static class Envelope {
35         public Envelope(Address to, Address from, Date arrival) { this.to = to; this.from = from; this.arrival = arrival; }
36         public final Date arrival;
37         public final Address to;
38         public final Address from;
39         public static Envelope augment(Envelope e, MIME.Headers h) {
40             if (e.from != null && e.to != null) return e;
41             Address to   = e.to   == null ? Address.parse(h.get("X-org.ibex.mail.headers.envelope.To"))   : e.to;
42             Address from = e.from == null ? Address.parse(h.get("X-org.ibex.mail.headers.envelope.From")) : e.from;
43             return new Envelope(to, from, e.arrival);
44         }
45     }
46
47
48     // Parsed Headers //////////////////////////////////////////////////////////////////////////////
49
50     public final Address     to;
51     public final Address     from;                // if multiple From entries, this is sender
52     public final Date        date;
53     public final Address     replyto;             // if none provided, this is equal to sender
54     public final String      subject;
55     public final String      messageid;
56     public final Address[]   cc;
57     public final Address[]   bcc;
58     public final Hashtable[] resent;
59     public final int         lines;                   // lines in the body  FIXME not accurate anymore
60
61
62     public Message(Stream stream, Envelope envelope) throws Malformed {
63         super(stream, null, false);
64         Vec resent = new Vec(), traces = new Vec();
65         this.envelope     = Envelope.augment(envelope, headers);
66         this.to           = headers.get("To") == null       ? envelope.to    : Address.parse(headers.get("To"));
67         this.from         = headers.get("From") == null     ? envelope.from  : Address.parse(headers.get("From"));
68         this.replyto      = headers.get("Reply-To") == null ? null           : Address.parse(headers.get("Reply-To"));
69         this.subject      = headers.get("Subject");
70         this.messageid    = headers.get("Message-Id");
71         this.cc           = Address.list(headers.get("Cc"));
72         this.bcc          = Address.list(headers.get("BCc"));
73         this.date         = parseDate(headers.get("Date"));
74         this.lines        = 0; /* FIMXE */
75         resent.copyInto(this.resent = new Hashtable[resent.size()]);
76         traces.copyInto(this.traces = new Trace[traces.size()]);
77     }
78
79
80     // Helpers /////////////////////////////////////////////////////////////////////////////
81
82     // http://www.jwz.org/doc/mid.html
83     private static final Random random = new Random();
84     public static String generateFreshMessageId() {
85         StringBuffer ret = new StringBuffer();
86         ret.append('<');
87         ret.append(Base36.encode(System.currentTimeMillis()));
88         ret.append('.');
89         ret.append(Base36.encode(random.nextLong()));
90         ret.append('.');
91         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
92         ret.append('>');
93         return ret.toString();
94     }
95
96     public static Date parseDate(String s) { return null; } // FIXME!!!
97    
98     //  use null-sender for error messages (don't send errors to the null addr)
99     public Message bounce(String reason) { throw new RuntimeException("bounce not implemented"); }  // FIXME!
100  
101     public String summary() {
102         return
103             "          Subject: " + subject + "\n" +
104             "     EnvelopeFrom: " + envelope.from + "\n" +
105             "       EnvelopeTo: " + envelope.to + "\n" +
106             "        MessageId: " + messageid;
107     }
108
109     public void dump(Stream s) {
110         s.setNewline("\r\n");
111         s.println(headers.raw);
112         s.println();
113         s.println(body);
114         s.flush();
115     }
116
117     public int size()        { return headers.raw.length() + 2 /* CRLF */ + body.length(); }
118     public String toString() { return headers.raw + "\r\n" + body; }
119
120
121     // SMTP Traces //////////////////////////////////////////////////////////////////////////////
122
123     public final Trace[]     traces;
124     public class Trace {
125         final String returnPath;
126         final Element[] elements;
127         public Trace(Stream stream) throws Trace.Malformed {
128             String retPath = stream.readln();
129             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
130             returnPath = retPath.substring(12).trim();
131             Vec el = new Vec();
132             while(true) {
133                 String s = stream.readln();
134                 if (s == null) break;
135                 if (!s.startsWith("Received:")) { stream.unread(s); break; }
136                 s = s.substring(9).trim();
137                 el.addElement(new Element(s));
138             }
139             elements = new Element[el.size()];
140             el.copyInto(elements);
141         }
142         public class Element {
143              String fromDomain;
144              String fromIP;
145              String toDomain;
146              String forWhom;
147              Date date;
148             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
149                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
150             public Element(String s) throws Trace.Malformed {
151                 StringTokenizer st = new StringTokenizer(s);
152                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
153                 fromDomain = st.nextToken();
154                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
155                 toDomain = st.nextToken();
156                 // FIXME not done yet
157             }
158         }
159         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
160     }
161
162     public static class Malformed extends Exception { public Malformed(String s) { super(s); } }
163
164 }
165
166         /*
167             if (key.startsWith("Resent-")) {
168                 if (resent.size() == 0 || key.startsWith("Resent-From")) resent.addElement(new Hashtable());
169                 ((Hashtable)resent.lastElement()).put(key.substring(7), val);
170             } else if (key.startsWith("Return-Path")) {
171                 stream.unread(s);
172                 traces.addElement(new Trace(stream));
173         */