outgoing smtp
[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 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 Trace[] traces;
36
37     public final Address envelopeFrom;
38     public final Address[] envelopeTo;
39
40     public Date arrival = null;         // 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     public static class StoredMessage extends Message {
51         public int uid;
52         public boolean deleted = false;
53         public boolean read = false;
54         public boolean answered = false;
55         public StoredMessage(LineReader rs) throws IOException, MailException.Malformed { super(rs); }
56     }
57
58     public class Trace {
59         final String returnPath;
60         final Element[] elements;
61         public Trace(LineReader lr) throws Trace.Malformed, IOException {
62             String retPath = lr.readLine();
63             if (!retPath.startsWith("Return-Path:")) throw new Trace.Malformed("trace did not start with Return-Path header");
64             returnPath = retPath.substring(12).trim();
65             Vec el = new Vec();
66             while(true) {
67                 String s = lr.readLine();
68                 if (s == null) break;
69                 if (!s.startsWith("Received:")) { lr.pushback(s); break; }
70                 s = s.substring(9).trim();
71                 el.addElement(new Element(s));
72             }
73             elements = new Element[el.size()];
74             el.copyInto(elements);
75         }
76         public class Element {
77              String fromDomain;
78              String fromIP;
79              String toDomain;
80              String forWhom;
81              Date date;
82             public Element(String fromDomain, String fromIP, String toDomain, String forWhom, Date date) {
83                 this.fromDomain=fromDomain; this.fromIP=fromIP; this.toDomain=toDomain; this.forWhom=forWhom; this.date=date; }
84             public Element(String s) throws Trace.Malformed {
85                 StringTokenizer st = new StringTokenizer(s);
86                 if (!st.nextToken().equals("FROM")) throw new Trace.Malformed("trace did note have a FROM element: " + s);
87                 fromDomain = st.nextToken();
88                 if (!st.nextToken().equals("BY")) throw new Trace.Malformed("trace did note have a BY element: " + s);
89                 toDomain = st.nextToken();
90                 // FIXME not done yet
91             }
92         }
93         public class Malformed extends Message.Malformed { public Malformed(String s) { super(s); } }
94     }
95
96     public static class Malformed extends MailException.Malformed { public Malformed(String s) { super(s); } }
97     public Message(LineReader rs) throws IOException, Malformed {
98         String key = null;
99         StringBuffer all = new StringBuffer();
100         replyto = null;
101         subject = null;
102         messageid = null;
103         cc = null;
104         bcc = null;
105         resent = null;
106         traces = null;
107         envelopeFrom = null;
108         envelopeTo = null;
109
110         headers = new Hashtable();
111         date = null; // FIXME
112         to = null;
113         from = null;
114         for(String s = rs.readLine(); s != null && !s.equals(""); s = rs.readLine()) {
115             all.append(s);
116             all.append("\r\n");
117             if (s.length() == 0 || Character.isSpace(s.charAt(0))) {
118                 if (key == null) throw new Malformed("Message began with a blank line; no headers");
119                 headers.put(key, headers.get(key) + s);
120                 continue;
121             }
122             if (s.indexOf(':') == -1) throw new Malformed("Header line does not contain colon: " + s);
123             key = s.substring(0, s.indexOf(':'));
124             for(int i=0; i<s.length(); i++)
125                 if (s.charAt(i) < 33 || s.charAt(i) > 126)
126                     throw new Malformed("Header key contains invalid character \"" + s.charAt(i) + "\"");
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
171     public String summary() {
172         return
173             "          Subject: " + m.subject + "\n" +
174             "     EnvelopeFrom: " + m.envelopeFrom + "\n" +
175             "       EnvelopeTo: " + m.envelopeTo + "\n" +
176             "        MessageId: " + m.messageid;
177     }
178
179     public Message bounce(String reason) {
180         //  use null-sender for error messages (don't send errors to the null addr)
181         // FIXME
182         return null;
183     }
184 }