7c5635f8c825ff925c1103f2f7b039346b22334c
[org.ibex.mail.git] / src / org / ibex / mail / Message.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.mail;
6 import org.ibex.crypto.*;
7 import org.ibex.util.*;
8 import org.ibex.mail.protocol.*;
9 import org.ibex.js.*;
10 import org.ibex.io.*;
11 import org.ibex.io.Fountain;
12 import java.util.*;
13 import java.net.*;
14 import java.io.*;
15
16 // FIXME: this is important: folded headers: can insert CRLF anywhere that whitespace appears (before the whitespace)
17 // FIXME: messages must NEVER contain 8-bit binary data; this is a violation of IMAP
18 // FIXME: RFC822 1,000-char limit per line [soft line limit (suggested): 78 chars /  hard line limit: 998 chars]
19
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 /** 
26  *  [immutable] This class encapsulates a message "floating in the
27  *  ether": RFC2822 data but no storage-specific flags or other
28  *  metadata.
29  */
30 public class Message extends MIME.Part {
31
32     // Parsed Headers //////////////////////////////////////////////////////////////////////////////
33
34     public final Address     to;
35     public final Address     from;                // if multiple From entries, this is sender
36     public final Address     envelopeFrom;
37     public final Address     envelopeTo;
38     public final Date        date;
39     public final Date        arrival;
40     public final Address     replyto;             // if none provided, this is equal to sender
41     public final String      subject;
42     public final String      messageid;
43     public final Address[]   cc;
44     public final Address[]   bcc;
45
46     public static Message newMessage(Fountain in) throws Malformed { return new Message(in); }
47
48     // FIXME
49     public static Message newMessage(Fountain in, Address from, Address to) throws Malformed {
50         StringBuffer sb = new StringBuffer();
51         if (from != null) sb.append("Return-Path: " + from.toString(true) + "\r\n");
52         Stream stream = in.getStream();
53         while(true) {
54             String s = stream.readln();
55             if (s == null) break;
56             if (to != null && s.toLowerCase().startsWith("envelope-to:")) continue;
57             if (s.toLowerCase().startsWith("return-path:")) continue;
58             if (s.length() == 0) {
59                 if (to != null) sb.append("Envelope-To: " + to.toString(true) + "\r\n");
60                 sb.append("\r\n");
61                 break;
62             }
63             sb.append(s);
64             sb.append("\r\n");
65         }
66         for(String s = stream.readln(); s != null; s = stream.readln()) {
67             sb.append(s);
68             sb.append("\r\n");
69         }
70         return new Message(new Fountain.StringFountain(sb.toString()));
71     }
72
73     private Message(Fountain in) throws Malformed {
74         super(in);
75         this.envelopeTo   = headers.get("Envelope-To") != null ? Address.parse(headers.get("Envelope-To")) : null;
76         this.envelopeFrom = headers.get("Return-Path") != null ? Address.parse(headers.get("Return-Path")) : null;
77         this.to           = headers.get("To") != null ? Address.parse(headers.get("To")) : this.envelopeTo;
78         this.from         = headers.get("From") != null ? Address.parse(headers.get("From")) : this.envelopeFrom;
79         this.replyto      = headers.get("Reply-To") == null ? null : Address.parse(headers.get("Reply-To"));
80         this.subject      = headers.get("Subject");
81         this.messageid    = headers.get("Message-Id");
82         this.cc           = Address.list(headers.get("Cc"));
83         this.bcc          = Address.list(headers.get("Bcc"));
84         this.date         = parseDate(headers.get("Date")) == null ? new Date() : parseDate(headers.get("Date"));
85         this.arrival      = this.date; // FIXME wrong; grab this from traces?
86     }
87
88
89     // Helpers /////////////////////////////////////////////////////////////////////////////
90
91     // http://www.jwz.org/doc/mid.html
92     private static final Random random = new Random();
93     public static String generateFreshMessageId() {
94         StringBuffer ret = new StringBuffer();
95         ret.append('<');
96         ret.append(Base36.encode(System.currentTimeMillis()));
97         ret.append('.');
98         ret.append(Base36.encode(random.nextLong()));
99         ret.append('.');
100         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
101         ret.append('>');
102         return ret.toString();
103     }
104
105     public static Date parseDate(String s) {
106         // FIXME!!! this must be robust
107         // date/time parsing: see spec, 3.3
108         return null;
109     }
110
111     // this is belived to be compliant with QSBMF (http://cr.yp.to/proto/qsbmf.txt)
112     public Message bounce(String reason) {
113         if (envelopeFrom==null || envelopeFrom.toString().equals("")) return null;
114
115         Headers h = new Headers(headers.getStream());
116         h.put("Envelope-To", envelopeFrom.toString());
117         h.put("Return-Path", "<>");
118         h.put("From",        "MAILER-DAEMON");
119         h.put("To",          envelopeFrom.toString());
120         h.put("Subject",     "failure notice");
121
122         String error =
123             "Hi. This is the Ibex Mail Server.  I'm afraid I wasn't able to deliver\r\n"+
124             "your message to the following addresses. This is a permanent error;\r\n"+
125             "I've given up.  Sorry it didn't work out\r\n."+
126             "\r\n"+
127             "<"+envelopeTo.toString()+">:\r\n"+
128             reason+"\r\n"+
129             "\r\n"+
130             "--- Below this line is a copy of the message.\r\n"+
131             "\r\n";
132
133         try {
134             return newMessage(new Fountain.Concatenate(new Fountain.StringFountain(h.getString()+"\r\n"+error), getBody()));
135         } catch (Message.Malformed e) {
136             Log.error(this, "caught Message.Malformed in Message.bounce(); this should never happen");
137             Log.error(this, e);
138             return null;
139         }
140     }
141
142     public String toString() { throw new RuntimeException("Message.toString() called"); }
143     public String summary() { return "[" + envelopeFrom + " -> " + envelopeTo + "] " + subject; }
144
145     public static class Malformed extends Exception { public Malformed(String s) { super(s); } }
146 }
147