6738dc81b98bc88b17616377ded9d5610ccb80b0
[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: messages must NEVER contain 8-bit binary data; this is a violation of IMAP
17 // FIXME: RFC822 1,000-char limit per line [soft line limit (suggested): 78 chars /  hard line limit: 998 chars]
18
19 // FEATURE: PGP-signature-parsing
20 // FEATURE: mailing list header parsing (?)
21 // FEATURE: threading as in http://www.jwz.org/doc/threading.html
22
23 /** 
24  *  [immutable] This class encapsulates a message "floating in the
25  *  ether": RFC2822 data but no storage-specific flags or other
26  *  metadata.
27  */
28 public class Message extends MIME.Part {
29
30     // Parsed Headers //////////////////////////////////////////////////////////////////////////////
31
32     public final Address     to;
33     public final Address     from;                // if multiple From entries, this is sender
34     public final Address     envelopeFrom;
35     public final Address     envelopeTo;
36     public final Date        date;
37     public final Date        arrival;
38     public final Address     replyto;             // if none provided, this is equal to sender
39     public final String      subject;
40     public final String      messageid;
41     public final Address[]   cc;
42     public final Address[]   bcc;
43
44     public static Message newMessage(Fountain in) throws Malformed { return new Message(in); }
45
46     public Message reply(Fountain in, Address from, boolean includeReInSubject) throws Malformed {
47         /*
48         Address to = null;
49         if (to==null) to = Address.parse(headers.get("reply-to"));
50         if (to==null) to = Address.parse(headers.get("from"));
51         if (to==null) to = envelopeFrom;
52         Message ret = newMessage(in, from, to);
53         ret.headers.put("In-Reply-To", messageid);
54         String references = headers.get("references");
55         ret.headers.put("References", messageid + (references==null?"":(" "+references)));
56         if (includeReInSubject && subject!=null && !subject.toLowerCase().trim().startsWith("re:"))
57             headers.put("subject", "Re: "+subject);
58         return ret;
59         */
60         // FIXME
61         return null;
62     }
63
64     // FIXME
65     //public static Message newMessage(Headers headers, Fountain body, Address from, Address to) throws Malformed {
66     //}
67
68     public static Message newMessage(Fountain in, Address from, Address to) throws Malformed {
69         StringBuffer sb = new StringBuffer();
70         if (from != null) sb.append("Return-Path: " + from.toString(true) + "\r\n");
71         Stream stream = in.getStream();
72         while(true) {
73             String s = stream.readln();
74             if (s == null || s.length() == 0) {
75                 if (to != null) sb.append("Envelope-To: " + to.toString(true) + "\r\n");
76                 sb.append("\r\n");
77                 break;
78             }
79             if (to != null && s.toLowerCase().startsWith("envelope-to:")) continue;
80             if (s.toLowerCase().startsWith("return-path:")) continue;
81             sb.append(s);
82             sb.append("\r\n");
83         }
84         for(String s = stream.readln(); s != null; s = stream.readln()) {
85             sb.append(s);
86             sb.append("\r\n");
87         }
88         return new Message(new Fountain.StringFountain(sb.toString()));
89     }
90
91     private Message(Fountain in) throws Malformed {
92         super(in);
93         this.envelopeTo   = headers.get("Envelope-To") != null ? Address.parse(headers.get("Envelope-To")) : null;
94         this.envelopeFrom = headers.get("Return-Path") != null ? Address.parse(headers.get("Return-Path")) : null;
95         this.to           = headers.get("To") != null ? Address.parse(headers.get("To")) : this.envelopeTo;
96         this.from         = headers.get("From") != null ? Address.parse(headers.get("From")) : this.envelopeFrom;
97         this.replyto      = headers.get("Reply-To") == null ? null : Address.parse(headers.get("Reply-To"));
98         this.subject      = headers.get("Subject");
99         this.messageid    = headers.get("Message-Id");
100         this.cc           = Address.list(headers.get("Cc"));
101         this.bcc          = Address.list(headers.get("Bcc"));
102         this.date         = parseDate(headers.get("Date")) == null ? new Date() : parseDate(headers.get("Date"));
103
104         // RFC2822 requires a "Date" field, so we synthesize one if missing
105         if (headers.get("Date") == null)
106             headers.set("Date", this.date.toString());   // FIXME: formatting
107
108         this.arrival      = this.date; // FIXME wrong; grab this from traces?
109     }
110
111
112     // Helpers /////////////////////////////////////////////////////////////////////////////
113
114     // http://www.jwz.org/doc/mid.html
115     private static final Random random = new Random();
116     public static String generateFreshMessageId() {
117         StringBuffer ret = new StringBuffer();
118         ret.append('<');
119         ret.append(Base36.encode(System.currentTimeMillis()));
120         ret.append('.');
121         ret.append(Base36.encode(random.nextLong()));
122         ret.append('.');
123         try { ret.append(InetAddress.getLocalHost().getHostName()); } catch (UnknownHostException e) { /* DELIBERATE */ }
124         ret.append('>');
125         return ret.toString();
126     }
127
128     public static Date parseDate(String s) {
129         // FIXME!!! this must be robust
130         // date/time parsing: see spec, 3.3
131         return null;
132     }
133
134     // this is belived to be compliant with QSBMF (http://cr.yp.to/proto/qsbmf.txt)
135     public Message bounce(String reason) {
136         if (envelopeFrom==null || envelopeFrom.toString().equals("")) return null;
137
138         Log.warn(Message.class, "bouncing message due to: " + reason);
139         Headers h = new Headers.Original(headers.getStream());
140         h = h.set(new String[] {
141             "Envelope-To", envelopeFrom.toString(),
142             "Return-Path", "<>",
143             "From",        "MAILER-DAEMON <>",
144             "To",          envelopeFrom.toString(),
145             "Subject",     "failure notice"
146         });
147
148         String error =
149             "Hi. This is the Ibex Mail Server.  I'm afraid I wasn't able to deliver\r\n"+
150             "your message to the following addresses. This is a permanent error;\r\n"+
151             "I've given up.  Sorry it didn't work out\r\n."+
152             "\r\n"+
153             "<"+envelopeTo.toString()+">:\r\n"+
154             reason+"\r\n"+
155             "\r\n"+
156             "--- Below this line is a copy of the message.\r\n"+
157             "\r\n";
158
159         try {
160             return newMessage(new Fountain.Concatenate(new Fountain.StringFountain(h.getString()+"\r\n"+error), getBody()));
161         } catch (Message.Malformed e) {
162             Log.error(this, "caught Message.Malformed in Message.bounce(); this should never happen");
163             Log.error(this, e);
164             return null;
165         }
166     }
167
168     public       String toString() { throw new RuntimeException("Message.toString() called"); }
169     public final String summary() { return "[" + envelopeFrom + " -> " + envelopeTo + "] " + subject; }
170
171     public static class Malformed extends MailException { public Malformed(String s) { super(s); } }
172 }
173