fixed get/gets mixup
[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 extends org.ibex.js.JSReflection {
35         public Envelope(Address from, Address to, 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.gets("X-org.ibex.mail.headers.envelope.To"))   : e.to;
42             Address from = e.from == null ? Address.parse(h.gets("X-org.ibex.mail.headers.envelope.From")) : e.from;
43             return new Envelope(from, to, 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
60     public Message(Stream stream, Envelope envelope) throws Malformed {
61         super(stream, null, false);
62         Vec resent = new Vec(), traces = new Vec();
63         this.envelope     = Envelope.augment(envelope, headers);
64         this.to           = headers.gets("To") == null       ? envelope.to    : Address.parse(headers.gets("To"));
65         this.from         = headers.gets("From") == null     ? envelope.from  : Address.parse(headers.gets("From"));
66         this.replyto      = headers.gets("Reply-To") == null ? null           : Address.parse(headers.gets("Reply-To"));
67         this.subject      = headers.gets("Subject");
68         this.messageid    = headers.gets("Message-Id");
69         this.cc           = Address.list(headers.gets("Cc"));
70         this.bcc          = Address.list(headers.gets("BCc"));
71         this.date         = parseDate(headers.gets("Date"));
72         resent.copyInto(this.resent = new Hashtable[resent.size()]);
73         traces.copyInto(this.traces = new Trace[traces.size()]);
74     }
75
76
77     // Helpers /////////////////////////////////////////////////////////////////////////////
78
79     // http://www.jwz.org/doc/mid.html
80     private static final Random random = new Random();
81     public static String generateFreshMessageId() {
82         StringBuffer ret = new StringBuffer();
83         ret.append('<');
84         ret.append(Base36.encode(System.currentTimeMillis()));
85         ret.append('.');
86         ret.append(Base36.encode(random.nextLong()));
87         ret.append('.');
88         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
89         ret.append('>');
90         return ret.toString();
91     }
92
93     public static Date parseDate(String s) { return null; } // FIXME!!!
94    
95     //  use null-sender for error messages (don't send errors to the null addr)
96     public Message bounce(String reason) { throw new RuntimeException("bounce not implemented"); }  // FIXME!
97  
98     public String summary() {
99         return
100             "          Subject: " + subject + "\n" +
101             "     EnvelopeFrom: " + envelope.from + "\n" +
102             "       EnvelopeTo: " + envelope.to + "\n" +
103             "        MessageId: " + messageid;
104     }
105
106     public void dump(Stream s) {
107         s.setNewline("\r\n");
108         s.println(headers.raw);
109         s.println();
110         s.println(body);
111         s.flush();
112     }
113
114     public int size()        { return headers.raw.length() + 2 /* CRLF */ + body.length(); }
115     public String toString() { return headers.raw + "\r\n" + body; }
116
117
118     // SMTP Traces //////////////////////////////////////////////////////////////////////////////
119
120     public final Trace[]     traces;
121     public class Trace {
122         final String returnPath;
123         final Element[] elements;
124         public Trace(Stream stream) throws Trace.Malformed {
125             String retPath = stream.readln();
126             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
127             returnPath = retPath.substring(12).trim();
128             Vec el = new Vec();
129             while(true) {
130                 String s = stream.readln();
131                 if (s == null) break;
132                 if (!s.startsWith("Received:")) { stream.unread(s); break; }
133                 s = s.substring(9).trim();
134                 el.addElement(new Element(s));
135             }
136             elements = new Element[el.size()];
137             el.copyInto(elements);
138         }
139         public class Element {
140              String fromDomain;
141              String fromIP;
142              String toDomain;
143              String forWhom;
144              Date date;
145             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
146                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
147             public Element(String s) throws Trace.Malformed {
148                 StringTokenizer st = new StringTokenizer(s);
149                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
150                 fromDomain = st.nextToken();
151                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
152                 toDomain = st.nextToken();
153                 // FIXME not done yet
154             }
155         }
156         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
157     }
158
159     public static class Malformed extends Exception { public Malformed(String s) { super(s); } }
160
161 }
162
163         /*
164             if (key.startsWith("Resent-")) {
165                 if (resent.size() == 0 || key.startsWith("Resent-From")) resent.addElement(new Hashtable());
166                 ((Hashtable)resent.lastElement()).put(key.substring(7), val);
167             } else if (key.startsWith("Return-Path")) {
168                 stream.unread(s);
169                 traces.addElement(new Trace(stream));
170         */