more bugfixes
[org.ibex.mail.git] / src / org / ibex / mail / protocol / IMAP.java
1 package org.ibex.mail.protocol;
2 import org.ibex.mail.*;
3 import org.ibex.util.*;
4 import org.ibex.mail.target.*;
5 import java.util.*;
6 import java.net.*;
7 import java.text.*;
8 import java.io.*;
9
10 // Relevant RFC's:
11 //   RFC 2060: IMAPv4
12 //   RFC 3501: IMAPv4 with clarifications
13 //   RFC 3691: UNSELECT
14 //   RFC 2971: ID
15
16 // FEATURE: MIME-queries
17 // FEATURE: READ-WRITE / READ-ONLY status on SELECT
18 // FEATURE: pipelining
19 // FEATURE: support [charset]
20 // FEATURE: \Noselect
21 // FEATURE: subscriptions
22
23 public class IMAP {
24
25     public static final float version = (float)0.1;
26
27     // API Class //////////////////////////////////////////////////////////////////////////////
28
29     public static final int
30         PEEK=0x1, BODYSTRUCTURE=0x2, ENVELOPE=0x4, FLAGS=0x8, INTERNALDATE=0x10,
31         RFC822=0x20, RFC822TEXT=0x40, RFC822SIZE=0x80, NEGATEHEADERS=0x100, UID=0x200, RFC822HEADER=0x400;
32
33     public static interface API {
34         public String[] capability();
35         public Hashtable id(Hashtable clientId);
36         public void copy(Query q, String to);
37         public void login(String u, String p);
38         public void logout();
39         public void unselect();
40         public void delete(String m);
41         public void create(String m);
42         public void append(String m, int flags, Date arrival, String body);
43         public void check();
44         public void noop();
45         public void close();
46         public void subscribe(String mailbox);
47         public void unsubscribe(String mailbox);
48         public int seen(String mailbox);
49         public int recent(String mailbox);
50         public int count(String mailbox);
51         public int uidNext(String mailbox);
52         public int uidValidity(String mailbox);
53         public int[] search(Query q, boolean uid);
54         public void rename(String from, String to);
55         public void select(String mailbox, boolean examineOnly);
56
57         public static interface Client {
58             public void expunge(int uid);
59             public void list(char separator, String mailbox);
60             public void fetch(int uidnum, int flags, int size, Message m);  // m may be null or incomplete
61         }
62
63         public void setFlags(Query q, int flags, boolean uid, Client c);
64         public void removeFlags(Query q, int flags, boolean uid, Client c);
65         public void addFlags(Query q, int flags, boolean uid, Client c);
66         public void expunge(Client client);
67         public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid, Client c);
68         public void lsub(String start, String ref, Client client);
69         public void list(String start, String ref, Client client);
70
71         public static interface Authenticator { public abstract Mailbox authenticate(String user, String pass); } 
72         public static class Exn extends MailException { public Exn(String s) { super(s); } }
73         public static class Bad extends Exn { public Bad(String s) { super(s); } }
74         public static class No extends Exn { public No(String s) { super(s); } }
75     }
76
77
78     // SocketWrapper //////////////////////////////////////////////////////////////////////////////
79
80     public static class SocketWrapper /* implements API */ {
81         // eventually this will implement the client side of an IMAP socket conversation
82     }
83
84     // MailboxWrapper //////////////////////////////////////////////////////////////////////////////
85
86     /** wraps an IMAP.API interface around a Mailbox */
87     public static class MailboxWrapper implements API {
88
89         Mailbox inbox = null;
90         Mailbox selected = null;
91         Mailbox selected() { if (selected == null) throw new API.Bad("no mailbox selected"); return selected; }
92         final API.Authenticator auth;
93
94         public static final char sep = '.';
95
96         private final Mailbox root;
97         public MailboxWrapper(Mailbox root, API.Authenticator auth) { this.root = root; this.auth = auth; }
98
99         private Mailbox getMailbox(String name, boolean create) {
100             Mailbox m = root;
101             for(StringTokenizer st = new StringTokenizer(name, sep + ""); st.hasMoreTokens();)
102                 if ((m = m.slash(st.nextToken(), create)) == null) throw new API.No("no such mailbox " + name);
103             return m;
104         }
105
106         // FEATURE: not accurate when a wildcard and subsequent non-wildcards both match a single component
107         public void lsub(String start, String ref, Client client) { list(start, ref, client); }
108         public void list(String start, String ref, Client client) {
109             if (ref.length() == 0 && start.length() == 0) { client.list(sep, ""); return; }
110             while (start.endsWith(""+sep)) start = start.substring(0, start.length() - 1);
111             if (ref.endsWith("%")) ref = ref + sep;
112             String[] children = (start.length() == 0 ? root : getMailbox(start, false)).children();
113             for(int i=0; i<children.length; i++) {
114                 String s = children[i], pre = ref, kid = start + (start.length() > 0 ? sep+"" : "") + s;                
115                 while(true) {
116                     if (pre.length() == 0) {
117                         if (s.length() == 0)       client.list(sep, kid);
118                     } else switch(pre.charAt(0)) {
119                         case sep:        if (s.length() == 0) list(kid, pre.substring(1), client);          break;
120                         case '%':        client.list(sep, kid); pre = pre.substring(1); s = "";    continue;
121                         case '*':        client.list(sep, kid); list(kid, pre, client); pre = pre.substring(1);     break;
122                         default:         if (s.length()==0)                                                 break;
123                                          if (s.charAt(0) != pre.charAt(0))                                  break;
124                                          s = s.substring(1); pre = pre.substring(1);                        continue;
125                     }
126                     break;
127                 }
128             }
129         }
130
131         public String[] capability() { return new String[] { "IMAP4rev1" /*, "UNSELECT", "ID"*/ }; }
132         public Hashtable id(Hashtable clientId) {
133             Hashtable response = new Hashtable();
134             response.put("name", IMAP.class.getName());
135             response.put("version", version + "");
136             response.put("os", System.getProperty("os.name", null));
137             response.put("os-version", System.getProperty("os.version", null));
138             response.put("vendor", "none");
139             response.put("support-url", "http://mail.ibex.org/");
140             return response;
141         }   
142
143         public void copy(Query q, String to0) {
144             Mailbox to = getMailbox(to0, false); for(Mailbox.Iterator it=selected.iterator(q);it.next();) to.add(it.cur()); }
145         public void login(String u, String p) { if ((inbox = auth.authenticate(u,p)) == null) throw new API.No("Login failed."); }
146         public void logout() { }
147         public void unselect() { selected = null; }
148         public void delete(String m0) { Mailbox m = getMailbox(m0, false); if (m != inbox) m.destroy(); }
149         public void create(String m) { if (!m.endsWith(""+sep)) getMailbox(m, true); }
150         public void append(String m, int flags, Date arrival, String body) {
151             getMailbox(m, false).add(new Message(null,null,body,arrival), flags); }
152         public void check() { }
153         public void noop() { }
154         public void close() { for(Mailbox.Iterator it=selected().iterator(Query.deleted()); it.next();) it.delete(); unselect(); }
155         public void expunge(Client c) { for(Mailbox.Iterator it = selected().iterator(Query.deleted());it.next();) expunge(it,c); }
156         public void expunge(Mailbox.Iterator it, Client client) { client.expunge(it.uid()); it.delete(); }
157         public void subscribe(String mailbox) { }
158         public void unsubscribe(String mailbox) { }
159         public int seen(String mailbox)        { return getMailbox(mailbox, false).count(Query.seen()); }
160         public int recent(String mailbox)      { return getMailbox(mailbox, false).count(Query.recent()); }
161         public int count(String mailbox)       { return getMailbox(mailbox, false).count(Query.all()); }
162         public int uidNext(String mailbox)     { return getMailbox(mailbox, false).uidNext(); }
163         public int uidValidity(String mailbox) { return getMailbox(mailbox, false).uidValidity(); }
164         public void select(String mailbox, boolean examineOnly) { selected = getMailbox(mailbox, false); }
165         public void setFlags(Query q, int f, boolean uid, Client c) { doFlags(q, f, c, uid, 0); }
166         public void addFlags(Query q, int f, boolean uid, Client c) { doFlags(q, f, c, uid, 1); }
167         public void removeFlags(Query q, int f, boolean uid, Client c) { doFlags(q, f, c, uid, -1); }
168         public int[] search(Query q, boolean uid) {
169             Vec vec = new Vec();
170             for(Mailbox.Iterator it = selected.iterator(q); it.next(); )
171                 vec.addElement(new Integer(uid ? it.uid() : it.num()));
172             int[] ret = new int[vec.size()];
173             for(int i=0; i<ret.length; i++) ret[i] = ((Integer)vec.elementAt(i)).intValue();
174             return ret;
175         }
176         private void doFlags(Query q, int flags, Client c, boolean uid, int style) {
177             for(Mailbox.Iterator it = selected.iterator(q);it.next();) {
178                 switch(style) {
179                     case -1: it.removeFlags(flags);
180                     case  0: it.setFlags(flags);
181                     case  1: it.addFlags(flags);
182                 }
183                 if (c != null) c.fetch(uid ? it.uid() : it.num(), it.flags(), -1, null);
184             }
185         }            
186         public void rename(String from0, String to) {
187             Mailbox from = getMailbox(from0, false);
188             if (from.equals(inbox))    { from.copy(Query.all(), getMailbox(to, true)); }
189             else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), getMailbox(to, true)); from.destroy(); }
190             else from.rename(to);
191         }
192         public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid, Client client) {
193             for(Mailbox.Iterator it = selected.iterator(q); it.next(); )
194                 client.fetch(uid ? it.uid() : it.num(), it.flags(), it.cur().rfc822size(), it.cur());
195         }
196     }
197
198
199     // Single Session Handler //////////////////////////////////////////////////////////////////////////////
200
201     /** takes an IMAP.API and exposes it to the world as an IMAP server on a TCP socket */
202     private static class Server extends Parser implements API.Client {
203         String selectedName = null;
204         Mailbox inbox = null;
205         final API api;
206         final Mailbox root;
207         final Socket conn;
208         final String vhost;
209         public void init() { }
210         public Server(Socket conn, Mailbox root, API.Authenticator auth) throws IOException {
211             this(conn, java.net.InetAddress.getLocalHost().getHostName(), root, auth); }
212         public Server(Socket conn, String vhost, Mailbox root, API.Authenticator auth) throws IOException {
213             super(conn);
214             this.api = new IMAP.MailboxWrapper(root, auth);
215             this.vhost = vhost; this.conn = conn; this.root = root;
216         }
217
218         // client callbacks
219         private Token[] lastfetch = null; // hack
220         private boolean lastuid = false;  // hack
221         public void fetch(int uidnum, int flags, int size, Message m) { fetch(null, lastfetch, uidnum, flags, size, lastuid, m); }
222         public void expunge(int uid) { star(uid + " EXPUNGE"); }
223         public void list(char separator, String mailbox) { star((lsub ? "LSUB":"LIST")+" () \"" + separator + "\" \""+mailbox+"\""); }
224         public void star(String s)    { println("* " + s); }
225
226         boolean lsub = false;
227
228         public boolean handleRequest() throws IOException {
229             star("OK " + vhost + " " + IMAP.class.getName() + " IMAP4rev1 [RFC3501] v" + version + " server ready");
230             for(String tag = null;; newline()) try {
231                 flush();
232                 boolean uid = false;
233                 tag = null; tag = token().atom();
234                 String command = token().atom();
235                 if (command.equalsIgnoreCase("UID")) { uid = true; command = token().atom(); }
236                 switch(((Integer)commands.get(command.toUpperCase())).intValue()) {
237                     case AUTHENTICATE: api.login(token().astring(), token().astring()); break;
238                     case LOGIN:        api.login(token().astring(), token().astring()); break;
239                     case LOGOUT:       api.logout(); star("BYE"); conn.close(); return false;
240                     case LIST:         lsub = false; api.list(token().q(), token().q(), this); break;
241                     case LSUB:         lsub = true; api.lsub(token().q(), token().q(), this); break;
242                     case SUBSCRIBE:    api.subscribe(token().q()); break;
243                     case UNSUBSCRIBE:  api.unsubscribe(token().atom()); break;
244                     case CAPABILITY:   star("CAPABILITY " + Printer.join(" ", api.capability())); break;
245                         //case ID:           id(); break;
246                     case RENAME:       api.rename(token().atom(), token().atom()); break;
247                     case EXAMINE:      api.select(token().astring(), true); break;
248                     case COPY:         api.copy(Query.set(uid, token().set()), token().q()); break;
249                     case DELETE:       api.delete(token().atom()); break;
250                     case CHECK:        api.check(); break;
251                     case NOOP:         api.noop(); break;
252                     case CLOSE:        api.close(); break;
253                     case EXPUNGE:      api.expunge(this); break;
254                     case UNSELECT:     api.unselect(); break;
255                     case CREATE:       api.create(token().astring()); break;
256                     case FETCH:        lastuid=uid; fetch(Query.set(uid, token().set()), token().l(), 0, 0, 0, uid, null); break;
257                     case SEARCH:       star("SEARCH " + Printer.join(api.search(query(), uid))); break;
258                     case SELECT: {
259                         String mailbox = token().astring();
260                         api.select(mailbox, false);
261                         star("FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
262                         star(api.count(mailbox)  + " EXISTS");
263                         star(api.recent(mailbox) + " RECENT");
264                         star("OK [UIDVALIDITY " + api.uidValidity(mailbox) + "] UIDs valid");
265                         break; }
266                     case STATUS: {
267                         String mailbox = token().atom();
268                         Token[] list = token().l();
269                         String response = "";
270                         for(int i=0; i<list.length; i++) {
271                             String s = list[i].atom();
272                             if (s.equals("MESSAGES"))    response += "MESSAGES "    + api.count(mailbox);
273                             if (s.equals("RECENT"))      response += "RECENT "      + api.seen(mailbox);
274                             if (s.equals("UIDNEXT"))     response += "UNSEEN "      + api.recent(mailbox);
275                             if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + api.uidValidity(mailbox);
276                             if (s.equals("UNSEEN"))      response += "UIDNEXT "     + api.uidNext(mailbox);
277                         }
278                         star("STATUS " + selectedName + " (" + response + ")");
279                         break;
280                     }
281                     case APPEND: { 
282                         String m = token().atom();
283                         int flags = 0;
284                         Date arrival = null;
285                         Token t = token();
286                         if (t.type == t.LIST)   { flags = t.flags();      t = token(); }
287                         if (t.type == t.QUOTED) { arrival = t.datetime(); t = token(); }
288                         api.append(m, flags, arrival, token().q());
289                         break; }
290                     case STORE: {
291                         Query q = uid ? Query.uid(token().set()) : Query.num(token().set());
292                         String s = token().atom().toUpperCase();
293                         int flags = token().flags();
294                         if (s.equals("FLAGS"))              api.setFlags(q,    flags, uid, null);
295                         else if (s.equals("+FLAGS"))        api.addFlags(q,    flags, uid, null);
296                         else if (s.equals("-FLAGS"))        api.removeFlags(q, flags, uid, null);
297                         else if (s.equals("FLAGS.SILENT"))  api.setFlags(q,    flags, uid, this);
298                         else if (s.equals("+FLAGS.SILENT")) api.addFlags(q,    flags, uid, this);
299                         else if (s.equals("-FLAGS.SILENT")) api.removeFlags(q, flags, uid, this);
300                         else throw new API.Bad("unknown STORE specifier " + s);
301                         break; }
302                     default: throw new API.Bad("unrecognized command \"" + command + "\"");
303                 }
304                 println(tag + " OK " + command + " Completed.");
305             } catch (API.Bad b) { println(tag==null ? "* BAD Invalid tag" : (tag + " Bad " + b.toString())); b.printStackTrace();
306             } catch (API.No n)  { println(tag==null ? "* BAD Invalid tag" : (tag + " No "  + n.toString())); n.printStackTrace(); }
307         }
308
309         /**
310          *   Parse a fetch request <i>or</i> emit a fetch reply.
311          *
312          *   To avoid duplicating tedious parsing logic, this function
313          *   performs both of the following tasks:
314          *      - parse the fetch request in Token[] t and return a fetch spec
315          *      - emit a fetch reply for the parsed spec with respect to message m
316          */
317         private void fetch(Query q, Token[] t, int uidnum, int flags, int size, boolean uid, Message m) {
318             lastfetch = t;
319             boolean e = m != null;
320             int spec = 0;                              // spec; see constants for flags
321             String[] headers = null;
322             int start = -1, end = -1;
323             StringBuffer r = new StringBuffer();       // reply
324             if (e) { r.append(uidnum); r.append(" FETCH ("); }
325             int initlen = r.length();
326             for(int i=0; i<t.length; i++) {
327                 if (r.length() > initlen) r.append(" ");
328                 String s = t[i].s.toUpperCase();
329                 if (!uid || !s.equals("UID")) r.append(s.equals("BODY.PEEK")?"BODY":s);
330                 if (s.equals("BODYSTRUCTURE")) {        spec|=BODYSTRUCTURE;if(e){r.append(" ");r.append(Printer.bodystructure(m));}
331                 } else if (s.equals("ENVELOPE")) {      spec|=ENVELOPE; if(e){r.append(" "); r.append(Printer.envelope(m));}
332                 } else if (s.equals("FLAGS")) {         spec|=FLAGS; if(e){r.append(" "); r.append(Printer.flags(flags));}
333                 } else if (s.equals("INTERNALDATE")) {  spec|=INTERNALDATE; if(e){r.append(" "); r.append(Printer.date(m.arrival));}
334                 } else if (s.equals("RFC822")) {        spec|=RFC822; if(e){r.append(" "); r.append(Printer.message(m));}
335                 } else if (s.equals("RFC822.TEXT")) {   spec|=RFC822TEXT; if(e){r.append(" ");r.append(Printer.qq(m.body));}
336                 } else if (s.equals("RFC822.HEADER")) { spec|=RFC822HEADER; if(e){r.append(" ");r.append(Printer.qq(m.allHeaders+"\r\n"));}
337                 } else if (s.equals("RFC822.SIZE")) {   spec|=RFC822SIZE; if(e){r.append(" "); r.append(m.rfc822size());}
338                 } else if (s.equals("UID")) {
339                     spec|=UID;
340                     if (e && !uid) { r.append(" "); r.append(uidnum); }
341                     /*FIXME: UID in nonuid fetch*/
342                 } else if (s.equals("BODY.PEEK") || s.equals("BODY")) {
343                     if (s.equalsIgnoreCase("BODY.PEEK")) spec |= PEEK;
344                     String payload = "";
345                     if (i<t.length - 1 && (t[i+1].type == Token.LIST)) {
346                         r.append("[");
347                         Token[] list = t[++i].l();
348                         String s2 = list.length == 0 ? "" : list[0].s.toUpperCase();
349                         r.append(s2);
350                         if (list.length == 0)                    { spec |= RFC822TEXT;   if(e) payload = m.body; }
351                         else if (s2.equals(""))                  { spec |= RFC822TEXT;   if(e) payload = m.body; }
352                         else if (s2.equals("TEXT"))              { spec |= RFC822TEXT;   if(e) payload = m.body; }
353                         else if (s2.equals("HEADER"))            { spec |= RFC822HEADER; if(e) payload = m.allHeaders+"\r\n"; }
354                         else if (s2.equals("HEADER.FIELDS"))     {
355                             spec |= RFC822HEADER;
356                             headers = t[i].l()[1].sl();
357                             if (e) r.append(" (");
358                             if(e) for(int j=0; j<headers.length; j++) {
359                                 r.append(headers[j] + (j<headers.length-1?" ":""));
360                                 if (m.headers.get(headers[j]) != null) payload += headers[j]+": "+m.headers.get(headers[j])+"\r\n";
361                             }
362                             payload += "\r\n";
363                             if (e) r.append(")]");
364                         } else if (s2.equals("HEADER.FIELDS.NOT")) {
365                             spec |= RFC822HEADER|NEGATEHEADERS;
366                             headers = t[i].l()[1].sl();
367                             if (e) r.append(" (");
368                             if (e) for(int j=0; j<headers.length; j++)
369                                 r.append(headers[j] + (j<headers.length-1?" ":""));
370                             if (e) r.append(")]");
371                             if(e) { OUTER: for(Enumeration x=m.headers.keys(); x.hasMoreElements();) {
372                                 String key = (String)x.nextElement();
373                                 for(int j=0; j<headers.length; j++) if (key.equalsIgnoreCase(headers[j])) continue OUTER;
374                                 payload += key + ": " + m.headers.get(key)+"\r\n";
375                             } }
376                             payload += "\r\n";
377                         } else if (s2.equals("MIME")) {            throw new API.Bad("MIME not supported");
378                         } else throw new API.Bad("unknown section type " + s2);
379                         if (i<t.length - 1 && (t[i+1].s != null && t[i+1].s.startsWith("<"))) {
380                             i++;
381                             String s3 = t[i].s.substring(1, t[i].s.indexOf('>'));
382                             int dot = s3.indexOf('.');
383                             start = dot == -1 ? Integer.parseInt(s3) : Integer.parseInt(s3.substring(0, s3.indexOf('.')));
384                             end = dot == -1 ? -1 : Integer.parseInt(s3.substring(s3.indexOf('.') + 1));
385                             if (e) { payload = payload.substring(start, end+1); r.append("<"+start+">"); }
386                         }
387                     } else {
388                         if (e) payload = m.body;
389                     }
390                     if (e) { r.append(" "); r.append(Printer.qq(payload)); }
391                 } else {
392                     throw new API.No("unknown fetch argument: " + s);
393                 }
394             }
395             if (e) {
396                 // FIXME hack
397                 if (uid) r.append(" UID " + uidnum);
398                 r.append(")");
399                 star(r.toString());
400             } else {
401                 api.fetch(q, spec, headers, start, end, uid, this);
402             }
403         }
404             
405         private static final Hashtable commands = new Hashtable();
406         private static final int UID = 0;          static { commands.put("UID", new Integer(UID)); }
407         private static final int AUTHENTICATE = 1; static { commands.put("AUTHENTICATE", new Integer(AUTHENTICATE)); }
408         private static final int LIST = 2;         static { commands.put("LIST", new Integer(LIST)); }
409         private static final int LSUB = 3;         static { commands.put("LSUB", new Integer(LSUB)); }
410         private static final int SUBSCRIBE = 4;    static { commands.put("SUBSCRIBE", new Integer(SUBSCRIBE)); }
411         private static final int UNSUBSCRIBE = 5;  static { commands.put("UNSUBSCRIBE", new Integer(UNSUBSCRIBE)); }
412         private static final int CAPABILITY = 6;   static { commands.put("CAPABILITY", new Integer(CAPABILITY)); }
413         private static final int ID = 7;           static { commands.put("ID", new Integer(ID)); }
414         private static final int LOGIN = 8;        static { commands.put("LOGIN", new Integer(LOGIN)); }
415         private static final int LOGOUT = 9;       static { commands.put("LOGOUT", new Integer(LOGOUT)); }
416         private static final int RENAME = 10;      static { commands.put("RENAME", new Integer(RENAME)); }
417         private static final int EXAMINE = 11;     static { commands.put("EXAMINE", new Integer(EXAMINE)); }
418         private static final int SELECT = 12;      static { commands.put("SELECT", new Integer(SELECT)); }
419         private static final int COPY = 13;        static { commands.put("COPY", new Integer(COPY)); }
420         private static final int DELETE = 14;      static { commands.put("DELETE", new Integer(DELETE)); }
421         private static final int CHECK = 15;       static { commands.put("CHECK", new Integer(CHECK)); }
422         private static final int NOOP = 16;        static { commands.put("NOOP", new Integer(NOOP)); }
423         private static final int CLOSE = 17;       static { commands.put("CLOSE", new Integer(CLOSE)); }
424         private static final int EXPUNGE = 18;     static { commands.put("EXPUNGE", new Integer(EXPUNGE)); }
425         private static final int UNSELECT = 19;    static { commands.put("UNSELECT", new Integer(UNSELECT)); }
426         private static final int CREATE = 20;      static { commands.put("CREATE", new Integer(CREATE)); }
427         private static final int STATUS = 21;      static { commands.put("STATUS", new Integer(STATUS)); }
428         private static final int FETCH = 22;       static { commands.put("FETCH", new Integer(FETCH)); }
429         private static final int APPEND = 23;      static { commands.put("APPEND", new Integer(APPEND)); }
430         private static final int STORE = 24;       static { commands.put("STORE", new Integer(STORE)); }
431         private static final int SEARCH = 25;      static { commands.put("SEARCH", new Integer(SEARCH)); }
432     }
433
434     public static class Parser {
435         private final Socket conn;
436         private final InputStream is;
437         private final PushbackReader r;
438         private final PrintWriter pw;
439         public Parser(Socket conn) throws IOException {
440             this.conn = conn;
441             this.is = conn.getInputStream();
442             this.pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
443             this.r = new PushbackReader(new InputStreamReader(this.is));
444         }
445         protected void println(String s) {
446             pw.println(s);
447             pw.flush();
448             if (log.length() > 0) {
449                 System.err.println("\033[31;1m"+log+"\033[33;0m");
450                 log = "";
451             }
452             System.err.println("\033[33;1m"+s+"\033[33;0m");
453         }
454         protected void flush() { pw.flush(); }
455         Query query() {
456             String s = null;
457             boolean not = false;
458             Query q = null;
459             while(true) {
460                 Token t = token();
461                 if (t.type == t.LIST) throw new API.No("nested queries not yet supported");
462                 else if (t.type == t.SET) return Query.num(t.set());
463                 s = t.atom();
464                 if (s.equals("NOT")) { not = true; continue; }
465                 if (s.equals("OR"))    return Query.or(query(), query());
466                 if (s.equals("AND"))   return Query.and(query(), query());
467                 break;
468             }
469             if (s.startsWith("UN"))        { not = true; s = s.substring(2); }
470             if (s.equals("ANSWERED"))        q = Query.answered();
471             else if (s.equals("DELETED"))    q = Query.deleted();
472             else if (s.equals("ALL"))        q = Query.all();
473             else if (s.equals("DRAFT"))      q = Query.draft();
474             else if (s.equals("FLAGGED"))    q = Query.flagged();
475             else if (s.equals("RECENT"))     q = Query.recent();
476             else if (s.equals("SEEN"))       q = Query.seen();
477             else if (s.equals("OLD"))      { not = true; q = Query.recent(); }
478             else if (s.equals("NEW"))        q = Query.and(Query.recent(), Query.not(Query.seen()));
479             else if (s.equals("KEYWORD"))    q = Query.header("keyword", token().flag());
480             else if (s.equals("HEADER"))     q = Query.header(token().astring(), token().astring());
481             else if (s.equals("BCC"))        q = Query.header("bcc", token().astring());
482             else if (s.equals("CC"))         q = Query.header("cc", token().astring());
483             else if (s.equals("FROM"))       q = Query.header("from", token().astring());
484             else if (s.equals("TO"))         q = Query.header("to", token().astring());
485             else if (s.equals("SUBJECT"))    q = Query.header("subject", token().astring());
486             else if (s.equals("LARGER"))     q = Query.size(token().n(), Integer.MAX_VALUE);
487             else if (s.equals("SMALLER"))    q = Query.size(Integer.MIN_VALUE, token().n());
488             else if (s.equals("BODY"))       q = Query.body(token().astring());
489             else if (s.equals("TEXT"))       q = Query.full(token().astring());
490             else if (s.equals("BEFORE"))     q = Query.arrival(new Date(0), token().date());
491             else if (s.equals("SINCE"))      q = Query.arrival(token().date(), new Date(Long.MAX_VALUE));
492             else if (s.equals("ON"))       { Date d = token().date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
493             else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), token().date());
494             else if (s.equals("SENTSINCE"))  q = Query.sent(token().date(), new Date(Long.MAX_VALUE));
495             else if (s.equals("SENTON"))   { Date d = token().date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
496             else if (s.equals("UID"))        q = Query.uid(token().set());
497             return q;
498         }
499
500         class Token {
501             public byte type;
502             public final String s;
503             public final Token[] l;
504             public final int n;
505             private static final byte NIL = 0;
506             private static final byte LIST = 1;
507             private static final byte QUOTED = 2;
508             private static final byte NUMBER = 3;
509             private static final byte ATOM = 4;
510             private static final byte BAREWORD = 5;
511             private static final byte SET = 6;
512             public Token() { n = 0; l = null; s = null; type = NIL; }
513             public Token(String s, boolean quoted) { this.s = s; l = null; type = quoted ? QUOTED : ATOM; n = 0; }
514             public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
515             public Token(int number) { n = number; l = null; s = null; type = NUMBER; }
516
517             public String flag() { if (type != ATOM) throw new API.Bad("expected a flag"); return s; }
518             public int n() { if (type != NUMBER) throw new API.Bad("expected number"); return n; }
519             public int nz() { int n = n(); if (n == 0) throw new API.Bad("expected nonzero number"); return n; }
520             public String  q() { if (type == NIL) return null; if (type != QUOTED) throw new API.Bad("expected qstring"); return s; }
521             public Token[] l() { if (type == NIL) return null; if (type != LIST) throw new API.Bad("expected list"); return l; }
522             public String[] sl() {
523                 if (type == NIL) return null;
524                 if (type != LIST) throw new API.Bad("expected list");
525                 String[] ret = new String[l.length];
526                 for(int i=0; i<ret.length; i++) ret[i] = l[i].s;
527                 return ret;
528             }
529             public String nstring() { if (type==NIL) return null; if (type==QUOTED) return s; throw new API.Bad("expected nstring"); }
530             public String astring() { if (type == ATOM || type == QUOTED) return s; throw new API.Bad("expected atom or string"); }
531
532             public int flags() {
533                 if (type != LIST) throw new API.Bad("expected flag list");
534                 int ret = 0;
535                 for(int i=0; i<l.length; i++) {
536                     String flag = l[i].s;
537                     if (flag.equals("\\Deleted"))       ret |= Mailbox.Flag.DELETED;
538                     else if (flag.equals("\\Seen"))     ret |= Mailbox.Flag.SEEN;
539                     else if (flag.equals("\\Flagged"))  ret |= Mailbox.Flag.FLAGGED;
540                     else if (flag.equals("\\Draft"))    ret |= Mailbox.Flag.DRAFT;
541                     else if (flag.equals("\\Answered")) ret |= Mailbox.Flag.ANSWERED;
542                     else if (flag.equals("\\Recent"))   ret |= Mailbox.Flag.RECENT;
543                 }
544                 return ret;
545             }
546             public int[] set() {
547                 if (type != ATOM) throw new API.Bad("expected a messageid set");
548                 Vec ids = new Vec();
549                 StringTokenizer st = new StringTokenizer(s, ",");
550                 while(st.hasMoreTokens()) {
551                     String s = st.nextToken();
552                     if (s.indexOf(':') != -1) {
553                         int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
554                         String end_s = s.substring(s.indexOf(':')+1);
555                         if (end_s.equals("*")) {
556                             ids.addElement(new Integer(start));
557                             ids.addElement(new Integer(Integer.MAX_VALUE));
558                         } else {
559                             int end = Integer.parseInt(end_s);
560                             for(int j=start; j<=end; j++) ids.addElement(new Integer(j));
561                         }
562                     } else {
563                         ids.addElement(new Integer(Integer.parseInt(s)));
564                         ids.addElement(new Integer(Integer.parseInt(s)));
565                     }
566                 }
567                 int[] ret = new int[ids.size()];
568                 for(int i=0; i<ret.length; i++) ret[i] = ((Integer)ids.elementAt(i)).intValue();
569                 return ret;
570             }
571             public Date date() {
572                 if (type != QUOTED && type != ATOM) throw new API.Bad("Expected quoted or unquoted date");
573                 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
574                 } catch (ParseException p) { throw new API.Bad("invalid date format; " + p); }
575             }
576             public Date datetime() {
577                 if (type != QUOTED && type != ATOM) throw new API.Bad("Expected quoted or unquoted datetime");
578                 try { return new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").parse(s.trim());
579                 } catch (ParseException p) { throw new API.Bad("invalid datetime format " + s + " : " + p); }
580             }
581             public String atom() {
582                 if (type != ATOM) throw new API.Bad("expected atom");
583                 for(int i=0; i<s.length(); i++) {
584                     char c = s.charAt(i);
585                     if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*')
586                         throw new API.Bad("invalid char in atom: " + c);
587                 }
588                 return s;
589             }
590         }
591
592         String log = "";
593         public char getc() throws IOException {
594             int ret = r.read();
595             if (ret == -1) throw new EOFException();
596             if (ret == '\n') {
597                 System.err.println("\033[31;1m"+log+"\033[33;0m");
598                 log = "";
599             } else if (ret != '\r') log += (char)ret;
600             return (char)ret;
601         }
602         public  char peekc() throws IOException {
603             int ret = r.read();
604             if (ret == -1) throw new EOFException();
605             r.unread(ret);
606             return (char)ret;
607         }
608         public  void fill(byte[] b) throws IOException {
609             int num = 0;
610             while (num < b.length) {
611                 int numread = is.read(b, num, b.length - num);
612                 if (numread == -1) throw new EOFException();
613                 num += numread;
614             }
615         }
616
617         public void newline() {
618             try {
619                 for(char c = peekc(); c == ' ';) { getc(); c = peekc(); };
620                 for(char c = peekc(); c == '\r' || c == '\n';) { getc(); c = peekc(); };
621             } catch (IOException e) {
622                 e.printStackTrace();
623             }
624         }
625
626         public Token token() {
627             try {
628                 Vec toks = new Vec();
629                 StringBuffer sb = new StringBuffer();
630                 char c = getc(); while (c == ' ') c = getc();
631                 if (c == '\r' || c == '\n') {
632                     throw new API.Bad("unexpected end of line");
633                 } if (c == '{') {
634                     while(peekc() != '}') sb.append(getc());
635                     int octets = Integer.parseInt(sb.toString());
636                     while(peekc() == ' ') getc();   // whitespace
637                     while (getc() != '\n' && getc() != '\r') { }
638                     byte[] bytes = new byte[octets];
639                     fill(bytes);
640                     return new Token(new String(bytes), true);
641                 } else if (c == '\"') {
642                     while(true) {
643                         c = getc();
644                         if (c == '\\') sb.append(getc());
645                         else if (c == '\"') break;
646                         else sb.append(c);
647                     }
648                     return new Token(sb.toString(), true);
649
650                     // NOTE: this is technically a violation of the IMAP grammar, since atoms like FOO[BAR should be legal
651                 } else if (c == ']' || c == ')') { return null;
652                 } else if (c == '[' || c == '(') {
653                     Token t;
654                     do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
655                     Token[] ret = new Token[toks.size()];
656                     toks.copyInto(ret);
657                     return new Token(ret);
658
659                 } else while(true) {
660                     sb.append(c);
661                     c = peekc();
662                     if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '[' || c == ']' ||
663                         c == '{' || c == '\n' || c == '\r')
664                         return new Token(sb.toString(), false);
665                     getc();
666                 }
667             } catch (IOException e) {
668                 e.printStackTrace();
669                 return null;
670             }
671         }
672     }
673
674     public static class Printer {
675         static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
676         static String quotify(Date d) { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
677         static String address(Address a) {return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
678         public static String addressList(Object a) {
679             if (a == null) return "NIL";
680             if (a instanceof Address) return "("+address((Address)a)+")";
681             Address[] aa = (Address[])a;
682             StringBuffer ret = new StringBuffer();
683             ret.append("(");
684             for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
685             ret.append(")");
686             return ret.toString();
687         }
688         static String flags(Mailbox.Iterator it) {
689             return
690                 (it.deleted()  ? "\\Deleted "  : "") +
691                 (it.seen()     ? "\\Seen "     : "") +
692                 (it.flagged()  ? "\\Flagged "  : "") +
693                 (it.draft()    ? "\\Draft "    : "") +
694                 (it.answered() ? "\\Answered " : "") +
695                 (it.recent()   ? "\\Recent "   : "");
696         }
697         static String flags(int flags) {
698             String ret = "(" +
699                 (((flags & Mailbox.Flag.DELETED) == Mailbox.Flag.DELETED) ? "\\Deleted "  : "") +
700                 (((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN)    ? "\\Seen "     : "") +
701                 (((flags & Mailbox.Flag.FLAGGED) == Mailbox.Flag.FLAGGED) ? "\\Flagged "  : "") +
702                 (((flags & Mailbox.Flag.DRAFT) == Mailbox.Flag.DRAFT)   ? "\\Draft "    : "") +
703                 (((flags & Mailbox.Flag.ANSWERED) == Mailbox.Flag.ANSWERED)? "\\Answered " : "") +
704                 (((flags & Mailbox.Flag.RECENT) == Mailbox.Flag.RECENT)  ? "\\Recent "   : "");
705             if (ret.endsWith(" ")) ret = ret.substring(0, ret.length() - 1);
706             return ret + ")";
707         }
708         static String bodystructure(Message m) {
709             // FIXME
710             return "(\"TEXT\" \"PLAIN\" () NIL NIL \"7BIT\" "+m.rfc822size()+" "+m.lines+")";
711         }
712         static String message(Message m) { return m.rfc822(); }
713         static String date(Date d) { return d.toString(); }
714         static String envelope(Message m) {
715             return
716                 "(" + quotify(m.arrival.toString()) +
717                 " " + quotify(m.subject) +          
718                 " " + addressList(m.from) +      
719                 " " + addressList(m.headers.get("sender")) +
720                 " " + addressList(m.replyto) + 
721                 " " + addressList(m.to) + 
722                 " " + addressList(m.cc) + 
723                 " " + addressList(m.bcc) + 
724                 " " + quotify((String)m.headers.get("in-reply-to")) +
725                 " " + quotify(m.messageid) +
726                 ")";
727         }
728         
729         public static String qq(String s) {
730             StringBuffer ret = new StringBuffer(s.length() + 20);
731             ret.append('{');
732             ret.append(s.length());
733             ret.append('}');
734             ret.append('\r');
735             ret.append('\n');
736             ret.append(s);
737             return ret.toString();
738         }
739         
740         private static String join(int[] nums) {
741             StringBuffer ret = new StringBuffer();
742             for(int i=0; i<nums.length; i++) {
743                 ret.append(nums[i]);
744                 if (i<nums.length-1) ret.append(' ');
745             }
746             return ret.toString();
747         }
748         private static String join(String delimit, String[] stuff) {
749             StringBuffer ret = new StringBuffer();
750             for(int i=0; i<stuff.length; i++) {
751                 ret.append(stuff[i]);
752                 if (i<stuff.length - 1) ret.append(delimit);
753             }
754             return ret.toString();
755         }
756     }
757
758
759     // Main //////////////////////////////////////////////////////////////////////////////
760
761     /** simple listener for testing purposes */
762     public static void main(String[] args) throws Exception {
763         ServerSocket ss = new ServerSocket(143);
764         for(;;) {
765             final Socket s = ss.accept();
766             new Thread() { public void run() { try {
767                 final Mailbox root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT+File.separatorChar+"imap", true);
768                 new Server(s, root,
769                             new API.Authenticator() {
770                                 public Mailbox authenticate(String u, String p) {
771                                     if (u.equals("megacz")&&p.equals("pass")) return root.slash("users",true).slash("megacz",true);
772                                     return null;
773                                 } } ).handleRequest();
774             } catch (Exception e) { e.printStackTrace(); } } }.start();
775         }
776     }
777 }