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