total overhaul; were using MIME and MIME.Part now
[org.ibex.mail.git] / src / org / ibex / mail / MIME.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 // FEATURE: MIME RFC2045, 2046, 2049
11
12 /** This class contains logic for encoding and decoding MIME multipart messages */
13 public class MIME {
14
15     public static class RFC2047 {
16         public static String decode(String s) {
17             /*
18             try { while (s.indexOf("=?") != -1) {
19                 String pre = s.substring(0, s.indexOf("=?"));
20                 s = s.substring(s.indexOf("=?") + 2);
21
22                 // MIME charset; FIXME use this
23                 String charset = s.substring(0, s.indexOf('?')).toLowerCase();
24                 s = s.substring(s.indexOf('?') + 1);
25
26                 String encoding = s.substring(0, s.indexOf('?')).toLowerCase();
27                 s = s.substring(s.indexOf('?') + 1);
28
29                 String encodedText = s.substring(0, s.indexOf("?="));
30
31                 if (encoding.equals("b"))      encodedText = new String(Base64.decode(encodedText));
32
33                 // except that ANY char can be endoed (unlike real qp)
34                 else if (encoding.equals("q")) encodedText = MIME.QuotedPrintable.decode(encodedText, true);
35                 else Log.warn(MIME.class, "unknown RFC2047 encoding \""+encoding+"\"");
36
37                 String post = s.substring(s.indexOf("?=") + 2);
38                 s = pre + encodedText + post;
39
40                 // FIXME re-encode when transmitting
41
42             } } catch (Exception e) {
43                 Log.warn(MIME.class, "error trying to decode RFC2047 encoded-word: \""+s+"\"");
44                 Log.warn(MIME.class, e);
45             }
46             */
47             return s;
48         }
49     }
50
51     public static class QuotedPrintable {
52         public static String decode(String s, boolean lax) {
53         //
54         //   =XX  -> hex representation, must be uppercase
55         //   9, 32, 33-60, 62-126 can be literal
56         //   9, 32 at end-of-line must get encoded
57         //   trailing whitespace must be deleted when decoding
58         //   =\n = soft line break
59         //   lines cannot be more than 76 chars long
60         //
61
62             // lax is used for RFC2047 headers; removes restrictions on which chars you can encode
63             return s;
64         }
65     }
66
67     // multipart/mixed       -- default
68     // multipart/parallel    -- order of components does not matter
69     // multipart/alternative -- same data, different versions
70     // multipart/digest      -- default content-type of components is message/rfc822
71     // message/rfc822        -- FIXME
72     // message/partial       -- not supported; see RFC 2046, section 5.2.2
73     // message/external-body -- not supported; see RFC 2046, section 5.2.3
74     // FIXME charsets  US-ASCII, ISO-8559-X, 
75     public static class Content extends org.ibex.js.JSReflection {
76         public final String    type;
77         public final String    subtype;
78         public final String    description;
79         public final String    id;
80         public final String    transferEncoding;
81         public final String    charset;
82         public final boolean   composite;
83         public final boolean   alternative;
84         public final Hashtable parameters = new Hashtable();
85         public Content(String header, String description, String id, String transferEncoding) {
86             this.id = id;
87             this.description = description;
88             this.transferEncoding = transferEncoding;
89             if (header == null) { type="text"; subtype="plain"; charset="us-ascii"; alternative=false; composite=false; return; }
90             header = header.trim();
91             if (header.indexOf('/') == -1) throw new MailException.Malformed("content-type lacks a forward slash: \""+header+"\"");
92             type = header.substring(0, header.indexOf('/')).toLowerCase();
93             header = header.substring(header.indexOf('/') + 1);
94             subtype = (header.indexOf(';') == -1) ? header.toLowerCase() : header.substring(0, header.indexOf(';')).toLowerCase();
95             composite   = type != null && (type.equals("message") || type.equals("multipart"));
96             alternative = composite && subtype.equals("alternative");
97             charset     = parameters.get("charset") == null ? "us-ascii" : parameters.get("charset").toString();
98             if (header.indexOf(';') == -1) return;
99             StringTokenizer st = new StringTokenizer(header.substring(header.indexOf(';') + 1), ";");
100             while(st.hasMoreTokens()) {
101                 String key = st.nextToken().trim();
102                 if (key.indexOf('=') == -1)
103                     throw new MailException.Malformed("content-type parameter lacks an equals sign: \""+key+"\"");
104                 String val = key.substring(key.indexOf('=')+1).trim();
105                 if (val.startsWith("\"") && val.endsWith("\"")) val = val.substring(1, val.length() - 2);
106                 key = key.substring(0, key.indexOf('=')+1).toLowerCase();
107                 parameters.put(key, val);
108             }
109         }
110     }
111
112     public static class Part extends org.ibex.js.JSReflection {
113         public final Content   content;
114         public final boolean   mime;                // true iff Mime-Version is 1.0
115         public final Headers   headers;
116         public final Part[]    subparts;
117         public final String    body;
118         private final boolean  last;
119
120         private Part[] parseParts(Stream stream) {
121             Vec v = new Vec();
122             // first part begins with a boundary delimiter
123             for(String s = stream.readln(); s != null; s = stream.readln())
124                 if (s.equals("--" + content.parameters.get("boundary"))) break;
125             while(true) {
126                 Part p = new Part(stream, (String)content.parameters.get("boundary"), true);
127                 v.addElement(p);
128                 if (p.last) break;
129             }
130             return (Part[])v.copyInto(new Part[v.size()]);
131         }
132        
133         public Part(Stream stream, String boundary, boolean assumeMime) throws MailException.Malformed {
134             this.headers     = new Headers(stream, assumeMime);
135             this.mime        = assumeMime | (headers.get("mime-version")!=null&&headers.get("mime-version").trim().equals("1.0"));
136             String ctype     = headers.get("content-type");
137             String encoding  = headers.get("content-transfer-encoding");
138             if (!(encoding == null || encoding.equals("7bit") || encoding.equals("8bit") || encoding.equals("binary") ||
139                   encoding.equals("quoted-printable") || encoding.equals("base64"))) {
140                 Log.warn(MIME.class, "unknown TransferEncoding \"" + encoding + "\"");
141                 ctype = "application/octet-stream";
142             }
143             content = new Content(ctype, headers.get("content-description"), headers.get("content-id"), encoding);
144             if (content.composite) { subparts = parseParts(stream); body = null; last = false; return; }
145             subparts = null;
146             boolean last = false;
147             StringBuffer body = new StringBuffer();
148             for(String s = stream.readln(); s != null; s = stream.readln()) {
149                 if (boundary != null && (s.equals(boundary) || s.equals(boundary + "--"))) {
150                     body.setLength(body.length() - 2);  // preceeding CRLF is part of delimiter
151                     last = s.equals(boundary + "--");
152                     break;
153                 }
154                 body.append(s);
155             }
156             if ("quoted-printable".equals(encoding)) this.body = MIME.QuotedPrintable.decode(body.toString(),false);
157             else if ("base64".equals(encoding)) this.body = new String(Base64.decode(body.toString()));
158             else this.body = body.toString();
159             this.last = last;
160         }
161     }
162
163     public static class Headers extends org.ibex.js.JSReflection {
164         private Hashtable head = new Hashtable();
165         public final String raw;
166         public String get(String s) { return (String)head.get(s.toLowerCase()); }
167         public static String uncomment(String val) {
168             boolean inquotes = false;
169             for(int i=0; i<val.length(); i++) {
170                 if (val.charAt(i) == '\"') inquotes = !inquotes;
171                 if (val.charAt(i) == '(' && !inquotes)
172                     val = val.substring(0, i) + val.substring(val.indexOf(i--, ')') + 1);
173             }
174             return val;
175         }
176         public Headers(Stream stream, boolean assumeMime) throws MailException.Malformed {
177             StringBuffer all = new StringBuffer();
178             String key = null;
179             for(String s = stream.readln(); s != null && !s.equals(""); s = stream.readln()) {
180                 all.append(s);
181                 all.append("\r\n");
182                 if (Character.isSpace(s.charAt(0))) {
183                     if (key == null) throw new MailException.Malformed("Message began with a blank line; no headers");
184                     head.put(key, head.get(key) + " " + s.trim());
185                     continue;
186                 }
187                 if (s.indexOf(':') == -1) throw new MailException.Malformed("Header line does not contain colon: " + s);
188                 key = s.substring(0, s.indexOf(':')).toLowerCase();
189                 for(int i=0; i<key.length(); i++)
190                     if (key.charAt(i) < 33 || key.charAt(i) > 126)
191                         throw new MailException.Malformed("Header key \""+key+"\" contains invalid character \"" + key.charAt(i) + "\"");
192                 String val = s.substring(s.indexOf(':') + 1).trim();
193                 if (get(key) != null) val = get(key) + " " + val; // just append it to the previous one;
194                 head.put(key, val);
195             }
196             this.raw = all.toString();
197
198             Enumeration e = head.keys();
199             boolean mime = assumeMime | (get("mime-version") != null && get("mime-version").trim().equals("1.0"));
200             while(e.hasMoreElements()) {
201                 String k = (String)e.nextElement();
202                 String v = (String)head.get(k);
203                 if (mime) k = MIME.RFC2047.decode(k);
204                 v = uncomment(v);
205                 if (mime) v = MIME.RFC2047.decode(v);
206                 head.put(k, v);
207             }
208         }
209     }
210 }