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