temporarily disable header rewriting; causing memory overflow
[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         public final int       lines;
119         private final boolean  last;
120
121         private Part[] parseParts(Stream stream) {
122             Vec v = new Vec();
123             // first part begins with a boundary delimiter
124             for(String s = stream.readln(); s != null; s = stream.readln())
125                 if (s.equals("--" + content.parameters.get("boundary"))) break;
126             while(true) {
127                 Part p = new Part(stream, (String)content.parameters.get("boundary"), true);
128                 v.addElement(p);
129                 //lines += p.lines;
130                 if (p.last) break;
131             }
132             return (Part[])v.copyInto(new Part[v.size()]);
133         }
134        
135         public Part(Stream stream, String boundary, boolean assumeMime) throws MailException.Malformed {
136             this.headers     = new Headers(stream, assumeMime);
137             this.mime        = assumeMime | (headers.gets("mime-version")!=null&&headers.gets("mime-version").trim().equals("1.0"));
138             String ctype     = headers.gets("content-type");
139             String encoding  = headers.gets("content-transfer-encoding");
140             if (!(encoding == null || encoding.equals("7bit") || encoding.equals("8bit") || encoding.equals("binary") ||
141                   encoding.equals("quoted-printable") || encoding.equals("base64"))) {
142                 Log.warn(MIME.class, "unknown TransferEncoding \"" + encoding + "\"");
143                 ctype = "application/octet-stream";
144             }
145             content = new Content(ctype, headers.gets("content-description"), headers.gets("content-id"), encoding);
146             //if (content.composite) { subparts = parseParts(stream); body = null; last = false; lines = 0; return; }
147             subparts = null;
148             boolean last = false;
149             int lines = 0;
150             StringBuffer body = new StringBuffer();
151             for(String s = stream.readln(); s != null; s = stream.readln()) {
152                 if (boundary != null && (s.equals(boundary) || s.equals(boundary + "--"))) {
153                     body.setLength(body.length() - 2);  // preceeding CRLF is part of delimiter
154                     last = s.equals(boundary + "--");
155                     break;
156                 }
157                 body.append(s);
158                 body.append("\r\n");
159                 lines++;
160             }
161             if ("quoted-printable".equals(encoding)) this.body = MIME.QuotedPrintable.decode(body.toString(),false);
162             else if ("base64".equals(encoding)) this.body = new String(Base64.decode(body.toString()));
163             else this.body = body.toString();
164             this.last = last;
165             this.lines = lines + headers.lines;
166         }
167     }
168
169     public static class Headers extends org.ibex.js.JSReflection {
170         private Hashtable head = new Hashtable();
171         public final int lines;
172         public final String raw;
173         public Object get(Object s) { return head.get(((String)s).toLowerCase()); }
174         public String gets(String s) { return (String)get(s); }
175         public static String uncomment(String val) {
176             boolean inquotes = false;
177             for(int i=0; i<val.length(); i++) {
178                 if (val.charAt(i) == '\"') inquotes = !inquotes;
179                 if (val.charAt(i) == '(' && !inquotes)
180                     val = val.substring(0, i) + val.substring(val.indexOf(i--, ')') + 1);
181             }
182             return val;
183         }
184         public Headers(Stream stream, boolean assumeMime) throws MailException.Malformed {
185             StringBuffer all = new StringBuffer();
186             String key = null;
187             int lines = 0;
188             for(String s = stream.readln(); s != null && !s.equals(""); s = stream.readln()) {
189                 all.append(s);
190                 all.append("\r\n");
191                 lines++;
192                 if (Character.isSpace(s.charAt(0))) {
193                     if (key == null) throw new MailException.Malformed("Message began with a blank line; no headers");
194                     head.put(key, head.get(key) + " " + s.trim());
195                     continue;
196                 }
197                 if (s.indexOf(':') == -1) throw new MailException.Malformed("Header line does not contain colon: " + s);
198                 key = s.substring(0, s.indexOf(':')).toLowerCase();
199                 for(int i=0; i<key.length(); i++)
200                     if (key.charAt(i) < 33 || key.charAt(i) > 126)
201                         throw new MailException.Malformed("Header key \""+key+"\" contains invalid character \"" + key.charAt(i) + "\"");
202                 String val = s.substring(s.indexOf(':') + 1).trim();
203                 if (get(key) != null) val = get(key) + " " + val; // just append it to the previous one;
204                 head.put(key, val);
205             }
206             this.raw = all.toString();
207             this.lines = lines;
208
209             Enumeration e = head.keys();
210             boolean mime = assumeMime | (gets("mime-version") != null && gets("mime-version").trim().equals("1.0"));
211             /*
212             while(e.hasMoreElements()) {
213                 String k = (String)e.nextElement();
214                 String v = (String)head.get(k);
215                 if (mime) k = MIME.RFC2047.decode(k);
216                 v = uncomment(v);
217                 if (mime) v = MIME.RFC2047.decode(v);
218                 head.put(k, v);
219             }
220             */
221         }
222     }
223 }