rename MailboxTree -> MailTree
[org.ibex.mail.git] / src / org / ibex / mail / IMAP.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.mail;
6 import org.ibex.io.*;
7 import org.ibex.net.*;
8 import org.ibex.crypto.*;
9 import org.ibex.mail.*;
10 import org.ibex.util.*;
11 import org.ibex.mail.target.*;
12 import java.util.*;
13 import java.net.*;
14 import java.text.*;
15 import java.io.*;
16  
17 // FEATURE: IDLE extension for blackberries
18
19 // FIXME: this is valid    LSUB "" asdfdas%*%*%*%*SFEFGWEF
20 // FIXME: be very careful about where/when we quotify stuff
21 // FIXME: 'UID FOO 100:*' must match at least one message even if all UIDs less than 100
22 // FIXME: LIST should return INBOX if applicable
23
24 // Relevant RFC's:
25 //   RFC 2060: IMAPv4
26 //   RFC 3501: IMAPv4 with clarifications
27 //   RFC 3691: UNSELECT
28 //   RFC 2971: ID
29
30 // to review
31 //   RFC 4466
32 //   RFC 4469
33
34 // FEATURE: make sure we're being case-insensitive enough; probably want to upcase atom()
35 // FEATURE: MIME-queries and BODYSTRUCTURE
36 // FEATURE: READ-WRITE / READ-ONLY status on SELECT
37 // FEATURE: pipelining
38 // FEATURE: support [charset]
39 // FEATURE: \Noselect
40 // FEATURE: subscriptions
41 // FEATURE: tune for efficiency
42 // FEATURE: STARTTLS
43 // FEATURE: asynchronous client notifications (need to re-read RFC)
44
45 public class IMAP {
46
47     public IMAP() { }
48     public static final float version = (float)0.2;
49
50     // API Class //////////////////////////////////////////////////////////////////////////////
51
52     public static interface Client {
53         public void expunge(int uid);
54         public void list(char separator, String mailbox, boolean lsub, boolean phantom);
55         public void fetch(int num, int flags, int size, Message m, int muid);  // m may be null or incomplete
56     }
57
58     public static interface Server {
59         public void      setClient(IMAP.Client client);
60         public String[]  capability();
61         public Hashtable id(Hashtable clientId);
62         public void      copy(Query q, String to);
63         public void      logout();
64         public void      unselect();
65         public void      delete(String m);
66         public void      create(String m);
67         public void      append(String m, int flags, Date arrival, String body);
68         public void      check();
69         public void      noop();
70         public void      close();
71         public void      subscribe(String mailbox);
72         public void      unsubscribe(String mailbox);
73         public int       unseen(String mailbox);
74         public int       recent(String mailbox);
75         public int       count(String mailbox);
76         public int       count();
77         public int       maxuid();
78         public int       uidNext(String mailbox);
79         public int       uidValidity(String mailbox);
80         public int[]     search(Query q, boolean uid);
81         public void      rename(String from, String to);
82         public void      select(String mailbox, boolean examineOnly);
83         public void      setFlags(Query q, int flags, boolean uid, boolean silent);
84         public void      removeFlags(Query q, int flags, boolean uid, boolean silent);
85         public void      addFlags(Query q, int flags, boolean uid, boolean silent);
86         public void      expunge();
87         public void      fetch(Query q, int spec, String[] headers, int start, int end, boolean uid);
88         public void      lsub(String start, String ref);
89         public void      list(String start, String ref);
90         public static class Exn extends MailException { public Exn(String s) { super(s); } }
91         public static class Bad extends Exn { public Bad(String s) { super(s); } }
92         public static class No extends Exn { public No(String s) { super(s); } }
93     }
94
95
96     // MailboxWrapper //////////////////////////////////////////////////////////////////////////////
97
98     /** wraps an IMAP.Server interface around a Mailbox */
99     public static class MailboxWrapper implements Server {
100
101         public static final char sep = '.';
102
103         Mailbox inbox = null;
104         Mailbox selected = null;
105         MailTree root = null;
106         Mailbox selected() { if (selected == null) throw new Bad("no mailbox selected"); return selected; }
107         final Login auth;
108         final Client client;
109
110         public MailboxWrapper(Login auth, Client c) { this.auth=auth; this.client=c;}
111         public void setClient(IMAP.Client client) { }
112
113         private String dirname(String name) { return name.substring(0, name.lastIndexOf(sep)); }
114         private String basename(String name) { return name.substring(name.lastIndexOf(sep)+1); }
115         private Mailbox mailbox(String name, boolean create) { return mailbox(name, create, true); }
116         private Mailbox mailbox(String name, boolean create, boolean throwexn) {
117             if (name.equalsIgnoreCase("inbox")) return inbox;
118             MailTree mt =  mailboxTree(name, create, throwexn);
119             return mt==null ? null : mt.getMailbox();
120         }
121         private MailTree mailboxTree(String name, boolean create) { return mailboxTree(name, create, true); }
122         private MailTree mailboxTree(String name, boolean create, boolean throwexn) {
123             MailTree m = root;
124             for(StringTokenizer st = new StringTokenizer(name, sep + ""); st.hasMoreTokens();)
125                 if ((m = m.slash(st.nextToken(), create)) == null) {
126                     if (throwexn) throw new Server.No("no such mailbox " + name);
127                     return null;
128                 }
129             return m;
130         }
131
132         // FEATURE: not accurate when a wildcard and subsequent non-wildcards both match a single component
133         public void lsub(String start, String ref) { list(start, ref, true); }
134         public void list(String start, String ref) { list(start, ref, false); }
135         public void list(String start, String ref, boolean lsub) {
136
137             // FIXME this might be wrong
138             if (ref.equalsIgnoreCase("inbox")) { client.list(sep,"inbox",lsub,false); return; }
139
140             if (ref.length() == 0) { client.list(sep, start, lsub, false); return; }
141             while (start.endsWith(""+sep)) start = start.substring(0, start.length() - 1);
142             if (ref.endsWith("%")) ref = ref + sep;
143             String[] children = (start.length() == 0 ? root : mailboxTree(start, false)).children();
144             for(int i=0; i<children.length; i++) {
145                 String s = children[i], pre = ref, kid = start + (start.length() > 0 ? sep+"" : "") + s;                
146                 if (mailbox(kid, false) == null) continue;
147                 MailTree phant = mailboxTree(kid, false, false);
148                 if (phant != null) {
149                     boolean phantom = phant.getMailbox()==null;
150                     while(true) {
151                         if (pre.length() == 0) {
152                             if (s.length() == 0)       client.list(sep, kid, lsub, phantom);
153                         } else switch(pre.charAt(0)) {
154                             case sep:        if (s.length() == 0) list(kid, pre.substring(1), lsub);                    break;
155                             case '%':        client.list(sep,kid,lsub,phantom);pre=pre.substring(1); s = "";            continue;
156                             case '*':        client.list(sep,kid,lsub,phantom);list(kid,pre,lsub);pre=pre.substring(1); break;
157                             default:         if (s.length()==0)                                                         break;
158                                 if (s.charAt(0) != pre.charAt(0))                                          break;
159                                 s = s.substring(1); pre = pre.substring(1);                                continue;
160                         }
161                         break;
162                     }
163                 }
164             }
165         }
166
167         public String[] capability() { return new String[] { "IMAP4rev1" , "UNSELECT" /*, "ID"*/ }; }
168         public Hashtable id(Hashtable clientId) {
169             Hashtable response = new Hashtable();
170             response.put("name", IMAP.class.getName());
171             response.put("version", version + "");
172             response.put("os", System.getProperty("os.name", null));
173             response.put("os-version", System.getProperty("os.version", null));
174             response.put("vendor", "none");
175             response.put("support-url", "http://mail.ibex.org/");
176             return response;
177         }   
178
179         public void copy(Query q, String to) { copy(q, mailbox(to, false)); }
180         /*  */ void copy(Query q, Mailbox to) {
181             for(Mailbox.Iterator it=selected().iterator(q);it.next();) to.insert(it.cur(), it.getFlags() | Mailbox.Flag.RECENT); }
182
183         public void unselect() { selected = null; }
184
185         public void delete(String m0) { mailboxTree(dirname(m0),false).rmdir(basename(m0)); }
186
187         public void rename(String from0, String to) {
188             Mailbox from = mailbox(from0, false);
189             if (from.equals(inbox))                { from.copy(Query.all(), mailbox(to, true)); }
190             else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), mailbox(to, true)); delete(from0); }
191             else mailboxTree(dirname(from0), false)
192                      .rename(dirname(from0),
193                              mailboxTree(dirname(to),
194                                          true /* required by IMAP */),
195                              basename(to));
196         }
197
198         public void create(String m) { mailbox(m, true, false); }
199         public void append(String m,int f,Date a,String b) { try {
200             // FIXME: more efficient streaming here?
201             mailbox(m,false).insert(Message.newMessage(new Fountain.StringFountain(b)), f | Mailbox.Flag.RECENT);
202         } catch (Message.Malformed e) { throw new No(e.getMessage()); } }
203         public void check() { }
204         public void noop() { }
205         public void logout() { }
206         public void close() { for(Mailbox.Iterator it=selected().iterator(Query.deleted()); it.next();) it.delete(); }
207         public void expunge() { for(Mailbox.Iterator it = selected().iterator(Query.deleted());it.next();) expunge(it); }
208         public void expunge(Mailbox.Iterator it) { client.expunge(it.uid()); it.delete(); }
209         public void subscribe(String mailbox) { }
210         public void unsubscribe(String mailbox) { }
211         public int maxuid() {
212             int ret = 0;
213             Mailbox mb = selected();
214             if (mb == null) return 0;
215             for(Mailbox.Iterator it = mb.iterator(); it.next(); ) ret = it.uid();
216             return ret;
217         }
218         public int unseen(String mailbox)      { return mailbox(mailbox, false).count(Query.not(Query.seen())); }
219         public int recent(String mailbox)      { return mailbox(mailbox, false).count(Query.recent()); }
220         public int count(String mailbox)       { return mailbox(mailbox, false).count(Query.all()); }
221         public int count()                     { return selected().count(Query.all()); }
222         public int uidNext(String mailbox)     { return mailbox(mailbox, false).uidNext(); }
223         public int uidValidity(String mailbox) { return Math.abs(mailbox(mailbox, false).uidValidity()); }
224         public void select(String mailbox, boolean examineOnly) { selected = mailbox(mailbox, false); }
225
226         public int[] search(Query q, boolean uid) {
227             Vec.Int vec = new Vec.Int();
228             for(Mailbox.Iterator it = selected().iterator(q); it.next();) {
229                 vec.addElement(uid ? it.uid() : it.imapNumber());
230                 it.setFlags(it.getFlags() & ~Mailbox.Flag.RECENT);
231             }
232             return vec.dump();
233         }
234
235         public void setFlags(Query q, int f, boolean uid, boolean silent)    { doFlags(q, f, uid, 0, silent); }
236         public void addFlags(Query q, int f, boolean uid, boolean silent)    { doFlags(q, f, uid, 1, silent); }
237         public void removeFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, -1, silent); }
238         private void doFlags(Query q, int flags, boolean uid, int style, boolean silent) {
239             for(Mailbox.Iterator it = selected().iterator(q);it.next();) {
240                 // FIXME: what's going on here with the recent flag?
241                 //boolean recent = it.getFlag(Mailbox.Flag.RECENT);
242                 //try { throw new Exception("flags " + flags); } catch (Exception e) { Log.error(this, e); }
243                 if (style == -1)     it.setFlags(it.getFlags() & ~flags);
244                 else if (style == 0) it.setFlags(flags);
245                 else if (style == 1) it.setFlags(it.getFlags() | flags);
246                 //it.setFlag(Mailbox.Flag.RECENT, recent);
247                 if (!silent) client.fetch(it.imapNumber(), it.getFlags(), -1, null, it.uid());
248             }
249         }
250
251         public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid) {
252             for(Mailbox.Iterator it = selected().iterator(q); it.next(); ) {
253                 Message message = ((spec & (BODYSTRUCTURE | ENVELOPE | INTERNALDATE | FIELDS | FIELDSNOT | RFC822 |
254                                             RFC822TEXT | RFC822SIZE | HEADERNOT | HEADER)) != 0) ? it.cur() : null;
255                 long size = message == null ? 0 : message.getLength();
256                 client.fetch(it.imapNumber(), it.getFlags(), (int)size, message, it.uid());
257                 it.setFlags(it.getFlags() & ~Mailbox.Flag.RECENT);
258             }
259         }
260     }
261
262     // Single Session Handler //////////////////////////////////////////////////////////////////////////////
263
264     /** takes an IMAP.Server and exposes it to the world as an IMAP server on a TCP socket */
265     public static class Listener implements Client {
266         String selectedName = null;
267         Mailbox inbox = null;
268         MailTree root = null;
269         Server api;
270         Parser parser = null;
271         Connection conn = null;
272         Login auth;
273         public Listener(Login auth) { api = new IMAP.MailboxWrapper(this.auth = auth, this); }
274         Parser.Token token() { return parser.token(); }
275         Parser.Token token(boolean freak) { return parser.token(freak); }
276         void println(String s) {
277             conn.println(s);
278             //Log.info("", s);
279         }
280         void newline() { parser.newline(); }
281         Query query(int max) { return parser.query(max, maxn(true)); }
282
283         public void login(String u, String p) {
284             Object ret;
285             if ((ret = auth.login(u,p,IMAP.class)) == null) throw new Server.No("Login failed.");
286             if (ret instanceof IMAP.Server) {
287                 api = (IMAP.Server)ret;
288                 api.setClient(this);
289             } else {
290                 Account account = (Account)ret;
291                 ((MailboxWrapper)api).root = root = account.getMailbox(IMAP.class);
292                 MailTree ibt = root.slash("INBOX", false);
293                 Mailbox ib = ibt==null ? null : ibt.getMailbox();
294                 ((MailboxWrapper)api).inbox = inbox = ib;
295             }
296         }
297
298         private int maxn(boolean uid) { return uid ? api.maxuid() : api.count(); }
299
300         public void handleRequest(Connection conn) {
301             this.conn = conn;
302             parser = new Parser(conn);
303             conn.setTimeout(30 * 60 * 1000);
304             println("* OK " + conn.vhost + " " + IMAP.class.getName() + " IMAP4rev1 [RFC3501] v" + version + " server ready");
305             for(String tag = null;;) try {
306                 conn.flush();
307                 boolean uid = false;
308                 tag = null; Parser.Token tok = token(); if (tok == null) return; tag = tok.astring();
309                 String command = token().atom();
310                 if (command.equalsIgnoreCase("UID")) { uid = true; command = token().atom(); }
311                 int commandKey = ((Integer)commands.get(command.toUpperCase())).intValue();
312                 switch(commandKey) {
313                     case LOGIN:        login(token().astring(), token().astring()); break;
314                     case CAPABILITY:   println("* CAPABILITY " + Printer.join(" ", api.capability())); break;
315                     case AUTHENTICATE: throw new Server.No("AUTHENTICATE not supported");
316                     case LOGOUT:       api.logout(); println("* BYE"); conn.close(); return;
317                     case LIST:         api.list(token().q(), token().astring()); break; /*astring is a hack for EUDORA*/
318                     case LSUB:         api.lsub(token().q(), token().q()); break;
319                     case SUBSCRIBE:    api.subscribe(token().astring()); break;
320                     case UNSUBSCRIBE:  api.unsubscribe(token().astring()); break;
321                     case RENAME:       api.rename(token().astring(), token().astring()); break;
322                     case DELETE:       api.delete(token().atom()); break;
323                     case CHECK:        selected(); api.check(); break;
324                     case NOOP:         api.noop(); break;
325                     case CLOSE:        selected(); api.close(); break;
326                     case EXPUNGE:      selected(); api.expunge(); break;
327                     case UNSELECT:     selected(); api.unselect(); selected = false; break;
328                     case CREATE:       api.create(token().astring()); break;
329                     case FETCH:        selected(); lastuid = uid; fetch((uid
330                                                                          ? Query.uid(token().set(maxn(uid)))
331                                                                          : Query.imapNumber(token().set(maxn(uid)))),
332                                                                         lastfetch=token().lx(), 0, 0, 0, uid, 0); break;
333                     case COPY:         selected(); api.copy(uid
334                                                             ? Query.uid(token().set(maxn(uid)))
335                                                             : Query.imapNumber(token().set(maxn(uid))), token().astring()); break;
336                     case SEARCH: {
337                         selected();
338                         int[] result = api.search(query(maxn(uid)), uid);
339                         /*if (result.length > 0)*/ println("* SEARCH " + Printer.join(result));
340                         break;
341                     }
342                     case EXAMINE:
343                     case SELECT: {
344                         String mailbox = token().astring();
345                         api.select(mailbox, commandKey==EXAMINE);
346                         println("* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
347                         println("* " + api.count(mailbox)  + " EXISTS");
348                         println("* " + api.recent(mailbox) + " RECENT");
349                         println("* OK [UNSEEN " + api.unseen(mailbox) + "]");
350                         println("* OK [UIDVALIDITY " + api.uidValidity(mailbox) + "] UIDs valid");
351                         println("* OK [UIDNEXT " + api.uidNext(mailbox) + "]");
352                         println("* OK [PERMANENTFLAGS (\\Seen)]");
353                         selected = true;
354                         break; }
355                     case STATUS: {
356                         String mailbox = token().astring();  // hack for GNUS buggy client
357                         Parser.Token[] list = token().l();
358                         String response = "";
359                         for(int i=0; i<list.length; i++) {
360                             String s = list[i].atom().toUpperCase();
361                             if (i>0) response += " ";
362                             if (s.equals("MESSAGES"))    response += "MESSAGES "    + api.count(mailbox);
363                             if (s.equals("RECENT"))      response += "RECENT "      + api.recent(mailbox);
364                             if (s.equals("UIDNEXT"))     response += "UIDNEXT "     + api.uidNext(mailbox);
365                             if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + api.uidValidity(mailbox);
366                             if (s.equals("UNSEEN"))      response += "UNSEEN "      + api.unseen(mailbox);
367                         }
368                         println("* STATUS " + mailbox + " (" + response + ")");
369                         break;
370                     }
371                     case APPEND: { 
372                         String m = token().astring();
373                         int flags = 0;
374                         Date arrival = new Date();
375                         Parser.Token t = token();
376                         if (t.type == t.LIST)   { flags = t.flags();      t = token(); }
377                         Parser.Token t2 = token(false);
378                         if (t2 != null) { arrival = t.datetime(); t = t2; }
379                         api.append(m, flags, arrival, t.q());
380                         break; }
381                     case STORE: {
382                         selected();
383                         Query q = uid ? Query.uid(token().set(maxn(uid))) : Query.imapNumber(token().set(maxn(uid)));
384                         String s = token().atom().toUpperCase();
385                         int flags = token().flags();
386                         if (s.equals("FLAGS"))              api.setFlags(q,    flags, uid, false);
387                         else if (s.equals("+FLAGS"))        api.addFlags(q,    flags, uid, false);
388                         else if (s.equals("-FLAGS"))        api.removeFlags(q, flags, uid, false);
389                         else if (s.equals("FLAGS.SILENT"))  api.setFlags(q,    flags, uid, true);
390                         else if (s.equals("+FLAGS.SILENT")) api.addFlags(q,    flags, uid, true);
391                         else if (s.equals("-FLAGS.SILENT")) api.removeFlags(q, flags, uid, true);
392                         else throw new Server.Bad("unknown STORE specifier " + s);
393                         break; }
394                     default: throw new Server.Bad("unrecognized command \"" + command + "\"");
395                 }
396                 println(tag+" OK "+command+" Completed. " +
397                         (commandKey == LOGIN ? ("[CAPABILITY "+Printer.join(" ", api.capability())+"]") : ""));
398                 try {
399                     newline();
400                 } catch (Stream.EOF e) {
401                     Log.info(this, "connection closed");
402                     return;
403                 }
404             } catch (Server.Bad b) { println(tag==null ? "* BAD Invalid tag":(tag + " Bad " + b.toString())); Log.warn(this,b);
405             } catch (Server.No n)  { println(tag==null?"* BAD Invalid tag":(tag+" No "  + n.toString())); Log.warn(this,n);
406             }
407         }
408
409         private Parser.Token[] lastfetch = null; // hack
410         private boolean lastuid = false;  // hack
411         private boolean selected = false;
412         private void selected() { if (!selected) throw new Server.Bad("no mailbox selected"); }
413
414         // Callbacks //////////////////////////////////////////////////////////////////////////////
415
416         public void expunge(int uid) { println("* " + uid + " EXPUNGE"); }
417         public void fetch(int n, int f, int size, Message m, int muid) { fetch(m, lastfetch, n, f, size, lastuid, muid); }
418         public void list(char sep, String mb, boolean sub, boolean p) {
419             println("* " + (sub?"LSUB":"LIST")+" ("+(p?"\\Noselect":"")+") \""+sep+"\" \""+mb+"\"");}
420
421         /**
422          *   Parse a fetch request <i>or</i> emit a fetch reply.
423          *
424          *   To avoid duplicating tedious parsing logic, this function
425          *   performs both of the following tasks:
426          *      - parse the fetch request in Token[] t and return a fetch spec
427          *      - emit a fetch reply for the parsed spec with respect to message m
428          */
429         private void fetch(Object o, Parser.Token[] t, int num, int flags, int size, boolean uid, int muid) {
430             Query q   = o == null ? null : o instanceof Query ? (Query)o : null;
431             Message m = o == null ? null : o instanceof Message ? (Message)o : null;
432             boolean e = q == null;
433
434             // asynchronous flags update
435             if (size == -1) {
436                 println("* " + num + " FETCH (FLAGS " + Printer.flags(flags) + (uid?(" UID "+muid):"") + ")");
437                 return;
438             }
439
440             lastfetch = t;
441             int spec = 0;                              // spec; see constants for flags
442             String[] headers = null;
443             int start = -1, end = -1;
444             StringBuffer r = new StringBuffer();
445             if (e) { r.append(num); r.append(" FETCH ("); }
446             int initlen = r.length();
447             if (uid) {
448                 boolean good = false;
449                 for(int i=0; i<t.length; i++)
450                     if ((t[i].type == Parser.Token.QUOTED || t[i].type == Parser.Token.ATOM) &&
451                         t[i].astring().equalsIgnoreCase("UID")) good = true;
452                 if (!good) {
453                     Parser.Token[] t2 = new Parser.Token[t.length + 1];
454                     System.arraycopy(t, 0, t2, 0, t.length);
455                     t2[t2.length - 1] = parser.token("UID");
456                     lastfetch = (t = t2);
457                 }
458             }
459             if (t.length == 0 && (t[0].type == Parser.Token.QUOTED || t[0].type == Parser.Token.ATOM)) {
460                 if (t[0].astring().equalsIgnoreCase("ALL"))
461                     t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"),
462                                       parser.token("ENVELOPE"), parser.token("RFC822.SIZE") };
463                 else if (t[0].astring().equalsIgnoreCase("FULL"))
464                     t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"), parser.token("BODY"), 
465                                       parser.token("ENVELOPE"), parser.token("RFC822.SIZE") };
466                 else if (t[0].astring().equalsIgnoreCase("FAST"))
467                     t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"),
468                                       parser.token("RFC822.SIZE") };
469             }
470             boolean looked_at_body = false;
471             for(int i=0; i<t.length; i++) {
472                 if (r.length() > initlen) r.append(" ");
473                 if (t[i] == null || t[i].s == null) continue;
474                 String s = t[i].s.toUpperCase();
475                 r.append(s.equalsIgnoreCase("BODY.PEEK")?"BODY":s);
476                 if (s.equals("BODYSTRUCTURE")) {       spec|=BODYSTRUCTURE;if(e){r.append(" ");r.append(Printer.bodystructure(m));}
477                 } else if (s.equals("ENVELOPE")) {     spec|=ENVELOPE;     if(e){r.append(" ");r.append(Printer.envelope(m));}
478                 } else if (s.equals("FLAGS")) {        spec|=FLAGS;        if(e){r.append(" ");r.append(Printer.flags(flags));}
479                 } else if (s.equals("INTERNALDATE")) { spec|=INTERNALDATE; if(e){r.append(" ");r.append(Printer.date(m.arrival));}
480                 } else if (s.equals("RFC822")) {       spec|=RFC822;       if(e){r.append(" ");r.append(Printer.message(m));}
481                 } else if (s.equals("RFC822.TEXT")) {  spec|=RFC822TEXT;   if(e){r.append(" ");r.append(Printer.qq(m.getStream()));}
482                 } else if (s.equals("RFC822.HEADER")){ spec|=HEADER;       if(e){r.append(" ");r.append(Printer.qq(m.headers.getStream().append("\r\n")));}
483                 } else if (s.equals("RFC822.SIZE")) {  spec|=RFC822SIZE;   if(e){r.append(" ");r.append(m.getLength());}
484                 } else if (s.equals("UID")) {          spec|=UID;          if(e){r.append(" ");r.append(muid); }
485                 } else if (!(s.equals("BODY.PEEK") || s.equals("BODY"))) { throw new Server.No("unknown fetch argument: " + s);
486                 } else {
487                     if (s.equalsIgnoreCase("BODY.PEEK"))   spec |= PEEK;
488                     looked_at_body = true;
489                     if (i >= t.length - 1 || t[i+1].type != Parser.Token.LIST) {
490                         spec |= BODYSTRUCTURE;
491                         if (e) { r.append(" "); r.append(Printer.bodystructure(m)); } continue;
492                         //if (e) { r.append(" "); r.append(Printer.qq(m.getBody().getStream())); } continue;
493                     }
494                     Fountain payload = Fountain.Util.create("");
495                     r.append("[");
496                     Parser.Token[] list = t[++i].l();
497                     s = list.length == 0 ? "" : list[0].s.toUpperCase();
498                     r.append(s);
499                     if (list.length == 0)                   { spec |= RFC822TEXT;   if(e) payload = m; }
500                     else if (s.equals("") || s.equals("1")) { spec |= RFC822TEXT;   if(e) payload = m; }
501                     else if (s.equals("TEXT"))              { spec |= RFC822TEXT;   if(e) payload = m.getBody(); }
502                     else if (s.equals("HEADER"))            { spec |= HEADER;       if(e) payload = Fountain.Util.concat(m.headers, Fountain.Util.create("\r\n")); }
503                     else if (s.equals("HEADER.FIELDS"))     { spec |= FIELDS;       payload=Fountain.Util.create(headers(r,t[i].l()[1].sl(),false,m,e)); }
504                     else if (s.equals("HEADER.FIELDS.NOT")) { spec |= FIELDSNOT;    payload=Fountain.Util.create(headers(r,t[i].l()[1].sl(),true,m,e)); }
505                     else if (s.equals("MIME")) {              throw new Server.Bad("MIME not supported"); }
506                     else                                      throw new Server.Bad("unknown section type " + s);
507                     if (i<t.length - 1 && (t[i+1].s != null && t[i+1].s.startsWith("<"))) {
508                         i++;
509                         s = t[i].s.substring(1, t[i].s.indexOf('>'));
510                         int dot = s.indexOf('.');
511                         start = dot == -1 ? Integer.parseInt(s) : Integer.parseInt(s.substring(0, s.indexOf('.')));
512                         end = dot == -1 ? -1 : Integer.parseInt(s.substring(s.indexOf('.') + 1));
513                         if (e) {
514                             //payload = payload.substring(start, Math.min(end+1,payload.getLength())); r.append("<"+start+">");
515                             // FIXME
516                             throw new RuntimeException("this had to be disabled");
517                         }
518                     }
519                     if (e) { r.append("] "); r.append(Printer.qq(payload.getStream())); }
520                 }
521             }
522             if ((spec & PEEK) == 0 && looked_at_body && e)
523                 api.addFlags(Query.imapNumber(new int[] { num, num }), Mailbox.Flag.SEEN, false, false);
524             if (e) {
525                 r.append(")");
526                 println("* " + r.toString());
527             } else {
528                 api.fetch(q, spec, headers, start, end, uid);
529             }
530         }
531
532         private String headers(StringBuffer r, String[] headers, boolean negate, Message m, boolean e) {
533             String payload = "";
534             if (e) r.append(" (");
535             if (!negate) {
536                 if(e) for(int j=0; j<headers.length; j++) {
537                     r.append(headers[j] + (j<headers.length-1?" ":""));
538                     if (m.headers.get(headers[j]) != null) payload += headers[j]+": "+m.headers.get(headers[j])+"\r\n";
539                 }
540             } else {
541                 throw new Server.No("HEADERS.NOT temporarily disaled");
542                 /*
543                 if (e) for(int j=0; j<headers.length; j++) r.append(headers[j] + (j<headers.length-1?" ":""));
544                 if(e) { OUTER: for(Enumeration x=m.headers.keys(); x.hasMoreElements();) {
545                     String key = (String)x.nextElement();
546                     for(int j=0; j<headers.length; j++) if (key.equalsIgnoreCase(headers[j])) continue OUTER;
547                     payload += key + ": " + m.headers.get(key)+"\r\n";
548                 } }
549                 */
550             }
551             if (e) r.append(")");
552             return payload + "\r\n";
553         }
554
555         private static final Hashtable commands = new Hashtable();
556         private static final int UID = 0;          static { commands.put("UID", new Integer(UID)); }
557         private static final int AUTHENTICATE = 1; static { commands.put("AUTHENTICATE", new Integer(AUTHENTICATE)); }
558         private static final int LIST = 2;         static { commands.put("LIST", new Integer(LIST)); }
559         private static final int LSUB = 3;         static { commands.put("LSUB", new Integer(LSUB)); }
560         private static final int SUBSCRIBE = 4;    static { commands.put("SUBSCRIBE", new Integer(SUBSCRIBE)); }
561         private static final int UNSUBSCRIBE = 5;  static { commands.put("UNSUBSCRIBE", new Integer(UNSUBSCRIBE)); }
562         private static final int CAPABILITY = 6;   static { commands.put("CAPABILITY", new Integer(CAPABILITY)); }
563         private static final int ID = 7;           static { commands.put("ID", new Integer(ID)); }
564         private static final int LOGIN = 8;        static { commands.put("LOGIN", new Integer(LOGIN)); }
565         private static final int LOGOUT = 9;       static { commands.put("LOGOUT", new Integer(LOGOUT)); }
566         private static final int RENAME = 10;      static { commands.put("RENAME", new Integer(RENAME)); }
567         private static final int EXAMINE = 11;     static { commands.put("EXAMINE", new Integer(EXAMINE)); }
568         private static final int SELECT = 12;      static { commands.put("SELECT", new Integer(SELECT)); }
569         private static final int COPY = 13;        static { commands.put("COPY", new Integer(COPY)); }
570         private static final int DELETE = 14;      static { commands.put("DELETE", new Integer(DELETE)); }
571         private static final int CHECK = 15;       static { commands.put("CHECK", new Integer(CHECK)); }
572         private static final int NOOP = 16;        static { commands.put("NOOP", new Integer(NOOP)); }
573         private static final int CLOSE = 17;       static { commands.put("CLOSE", new Integer(CLOSE)); }
574         private static final int EXPUNGE = 18;     static { commands.put("EXPUNGE", new Integer(EXPUNGE)); }
575         private static final int UNSELECT = 19;    static { commands.put("UNSELECT", new Integer(UNSELECT)); }
576         private static final int CREATE = 20;      static { commands.put("CREATE", new Integer(CREATE)); }
577         private static final int STATUS = 21;      static { commands.put("STATUS", new Integer(STATUS)); }
578         private static final int FETCH = 22;       static { commands.put("FETCH", new Integer(FETCH)); }
579         private static final int APPEND = 23;      static { commands.put("APPEND", new Integer(APPEND)); }
580         private static final int STORE = 24;       static { commands.put("STORE", new Integer(STORE)); }
581         private static final int SEARCH = 25;      static { commands.put("SEARCH", new Integer(SEARCH)); }
582     }
583
584     public static class Parser {
585         private Stream stream;
586         public Parser(Stream from) { this.stream = from; }
587         public Token token(String s) { return new Token(s); }
588         protected Query query(int max, int maxuid) {
589             String s = null;
590             boolean not = false;
591             Query q = null;
592             Query ret = null;
593             while(true) {
594                 Parser.Token t = token(false);
595                 if (t == null) break;
596                 if (t.type == t.LIST) throw new Server.No("nested queries not yet supported FIXME");
597                 else if (t.type == t.SET) return Query.imapNumber(t.set(max));
598                 s = t.atom().toUpperCase();
599                 if (s.equals("NOT"))   return Query.not(query(max, maxuid));
600                 if (s.equals("OR"))    return Query.or(query(max, maxuid), query(max, maxuid));    // FIXME parse rest of list
601                 if (s.equals("AND"))   return Query.and(query(max, maxuid), query(max, maxuid));
602
603                 if (s.startsWith("UN"))        { not = true; s = s.substring(2); }
604                 if (s.equals("ANSWERED"))        q = Query.answered();
605                 else if (s.equals("DELETED"))    q = Query.deleted();
606                 else if (s.equals("ALL"))        q = Query.all();
607                 else if (s.equals("DRAFT"))      q = Query.draft();
608                 else if (s.equals("FLAGGED"))    q = Query.flagged();
609                 else if (s.equals("RECENT"))     q = Query.recent();
610                 else if (s.equals("SEEN"))       q = Query.seen();
611                 else if (s.equals("OLD"))      { not = true; q = Query.recent(); }
612                 else if (s.equals("NEW"))        q = Query.and(Query.recent(), Query.not(Query.seen()));
613                 else if (s.equals("KEYWORD"))    q = Query.header("keyword", token().flag());
614                 else if (s.equals("HEADER"))     q = Query.header(token().astring(), token().astring());
615                 else if (s.equals("BCC"))        q = Query.header("bcc", token().astring());
616                 else if (s.equals("CC"))         q = Query.header("cc", token().astring());
617                 else if (s.equals("FROM"))       q = Query.header("from", token().astring());
618                 else if (s.equals("TO"))         q = Query.header("to", token().astring());
619                 else if (s.equals("SUBJECT"))    q = Query.header("subject", token().astring());
620                 else if (s.equals("LARGER"))     q = Query.size(token().n(), Integer.MAX_VALUE);
621                 else if (s.equals("SMALLER"))    q = Query.size(Integer.MIN_VALUE, token().n());
622                 else if (s.equals("BODY"))       q = Query.body(token().astring());
623                 else if (s.equals("TEXT"))       q = Query.full(token().astring());
624                 else if (s.equals("BEFORE"))     q = Query.arrival(new Date(0), token().date());
625                 else if (s.equals("SINCE"))      q = Query.arrival(token().date(), new Date(Long.MAX_VALUE));
626                 else if (s.equals("ON"))       { Date d = token().date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
627                 else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), token().date());
628                 else if (s.equals("SENTSINCE"))  q = Query.sent(token().date(), new Date(Long.MAX_VALUE));
629                 else if (s.equals("SENTON"))   { Date d = token().date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
630                 else if (s.equals("UID"))        q = Query.uid(token().set(max));
631                 q = not ? Query.not(q) : q;
632                 ret = ret == null ? q : Query.and(ret, q);
633             }
634             return ret;
635         }
636
637         private static void bad(String s) { throw new Server.Bad(s); }
638         class Token {
639             public final byte type;
640             private final String s;
641             private final Parser.Token[] l;
642             private final int n;
643             private static final byte NIL = 0, LIST = 1, QUOTED = 2, NUMBER = 3, ATOM = 4, BAREWORD = 5, SET = 6;
644             public Token()                         { this.s = null; n = 0;      l = null; type = NIL; }
645             public Token(String s)                 { this(s, false); }
646             public Token(String s, boolean quoted) { this.s = s;    n = 0;      l = null; type = quoted ? QUOTED : ATOM;  }
647             public Token(Parser.Token[] list)      { this.s = null; n = 0;      l = list; type = LIST; }
648             public Token(int number)               { this.s = null; n = number; l = null; type = NUMBER; }
649
650             public String   flag()    { if (type != ATOM) bad("expected a flag"); return s; }
651             public int      n()       { if (type != NUMBER) bad("expected number"); return n; }
652             public int      nz()      { int n = n(); if (n == 0) bad("expected nonzero number"); return n; }
653             public String   q()       { if (type == NIL) return null; if (type != QUOTED) bad("expected qstring"); return s; }
654             public Parser.Token[]  l()       { if (type == NIL) return null; if (type != LIST) bad("expected list"); return l; }
655             public Parser.Token[]  lx()      {
656                 if (type == LIST) return l;
657                 Vec v = new Vec();
658                 v.addElement(this);
659                 while(true) {
660                     Parser.Token t = token(false);
661                     if (t == null) break;
662                     v.addElement(t);
663                 }
664                 Parser.Token[] ret = new Parser.Token[v.size()];
665                 v.copyInto(ret);
666                 return ret;
667             }
668             public String   nstring() { if (type==NIL) return null; if (type!=QUOTED) bad("expected nstring"); return s; }
669             public String   astring() {
670                 if (type != ATOM && type != QUOTED) bad("expected atom or string");
671                 if (s == null) bad("astring cannot be null");
672                 return s; }
673             public String[] sl() {
674                 if (type == NIL) return null;
675                 if (type != LIST) bad("expected list");
676                 String[] ret = new String[l.length];
677                 for(int i=0; i<ret.length; i++) ret[i] = l[i].s;
678                 return ret;
679             }
680             public int flags() {
681                 if (type != LIST) bad("expected flag list");
682                 int ret = 0;
683                 for(int i=0; i<l.length; i++) {
684                     String flag = l[i].s;
685                     if (flag.equals("\\Deleted"))       ret |= Mailbox.Flag.DELETED;
686                     else if (flag.equals("\\Seen"))     ret |= Mailbox.Flag.SEEN;
687                     else if (flag.equals("\\Flagged"))  ret |= Mailbox.Flag.FLAGGED;
688                     else if (flag.equals("\\Draft"))    ret |= Mailbox.Flag.DRAFT;
689                     else if (flag.equals("\\Answered")) ret |= Mailbox.Flag.ANSWERED;
690                     else if (flag.equals("\\Recent"))   ret |= Mailbox.Flag.RECENT;
691                 }
692                 return ret;
693             }
694             public int[] set(int largest) {
695                 if (type != ATOM) bad("expected a messageid set");
696                 Vec.Int ids = new Vec.Int();
697                 StringTokenizer st = new StringTokenizer(s, ",");
698                 while(st.hasMoreTokens()) {
699                     String s = st.nextToken();
700                     if (s.indexOf(':') == -1) {
701                         if (s.equals("*")) {
702                             ids.addElement(largest);
703                             ids.addElement(largest);
704                         } else {
705                             ids.addElement(Integer.parseInt(s));
706                             ids.addElement(Integer.parseInt(s));
707                         }
708                         continue; }
709                     int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
710                     String end_s = s.substring(s.indexOf(':')+1);
711                     int end = end_s.equals("*") ? largest : Integer.parseInt(end_s);
712                     for(int j=Math.min(start,end); j<=Math.max(start,end); j++) {
713                         ids.addElement(j);
714                         ids.addElement(j);
715                     }
716                 }
717                 return ids.dump();
718             }
719             public Date date() {
720                 if (type != QUOTED && type != ATOM) bad("Expected quoted or unquoted date");
721                 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
722                 } catch (ParseException p) { throw new Server.Bad("invalid date format; " + p); }
723             }
724             public Date datetime() {
725                 if (type != QUOTED) bad("Expected quoted datetime");
726                 try { return new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss zzzz").parse(s.trim());
727                 } catch (ParseException p) { throw new Server.Bad("invalid datetime format " + s + " : " + p); }
728             }
729             public String atom() {
730                 if (type != ATOM) bad("expected atom");
731                 for(int i=0; i<s.length(); i++) {
732                     char c = s.charAt(i);
733                     if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*' || c == '\"' | c == '\\')
734                         bad("invalid char in atom: " + c);
735                 }
736                 return s;
737             }
738         }
739
740         public void newline() { stream.readln(); }
741
742         public Token token() { return token(true); }
743         public Token token(boolean freak) {
744             Vec toks = new Vec();
745             StringBuffer sb = new StringBuffer();
746             char c = stream.getc(); while (c == ' ') c = stream.getc();
747             if (c == '\r' || c == '\n') { if (freak) bad("unexpected end of line"); return null; }
748             else if (c == '{') {
749                 while(stream.peekc() != '}') sb.append(stream.getc());
750                 stream.getc();
751                 stream.println("+ Ready when you are...");
752                 int octets = Integer.parseInt(sb.toString());
753                 while(stream.peekc() == ' ') stream.getc();   // whitespace
754                 while(stream.peekc() == '\n' || stream.peekc() == '\r') stream.getc();
755                 byte[] bytes = new byte[octets];
756                 int numread = 0;
757                 while(numread < bytes.length) {
758                     int n = stream.read(bytes, numread, bytes.length - numread);
759                     if (n == -1) bad("end of stream while reading IMAP qstring");
760                     numread += n;
761                 }
762                 return new Token(new String(bytes), true);
763             } else if (c == '\"') {
764                 while(true) {
765                     c = stream.getc();
766                     if (c == '\\') sb.append(stream.getc());
767                     else if (c == '\"') break;
768                     else sb.append(c);
769                 }
770                 return new Token(sb.toString(), true);
771                 
772                 // NOTE: this is technically a violation of the IMAP grammar, since atoms like FOO[BAR should be legal
773             } else if (c == ']' || c == ')') { return null;
774             } else if (c == '[' || c == '(') {
775                 Token t;
776                 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
777                 Token[] ret = new Token[toks.size()];
778                 toks.copyInto(ret);
779                 return new Token(ret);
780                 
781             } else while(true) {
782                 sb.append(c);
783                 c = stream.peekc();
784                 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '[' || c == ']' ||
785                     c == '{' || c == '\n' || c == '\r')
786                     return new Token(sb.toString(), false);
787                 stream.getc();
788             }
789         }
790     }
791     
792     public static class Printer {
793             static String quotify(String s){
794                 return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
795             static String quotify(Date d) {
796                 return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
797             static String address(Address a) {
798                 return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
799             public static String addressList(Object a) {
800                 if (a == null) return "NIL";
801                 if (a instanceof Address) return "("+address((Address)a)+")";
802                 if (a instanceof String) return "("+address(Address.parse((String)a))+")";
803                 Address[] aa = (Address[])a;
804                 StringBuffer ret = new StringBuffer();
805                 ret.append("(");
806                 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
807                 ret.append(")");
808                 return ret.toString();
809             }
810             static String flags(Mailbox.Iterator it) {
811                 return
812                     ((it.getFlags() & Mailbox.Flag.DELETED)!=0  ? "\\Deleted "  : "") +
813                     ((it.getFlags() & Mailbox.Flag.SEEN)!=0     ? "\\Seen "     : "") +
814                     ((it.getFlags() & Mailbox.Flag.FLAGGED)!=0  ? "\\Flagged "  : "") +
815                     ((it.getFlags() & Mailbox.Flag.DRAFT)!=0    ? "\\Draft "    : "") +
816                     ((it.getFlags() & Mailbox.Flag.ANSWERED)!=0 ? "\\Answered " : "") +
817                     ((it.getFlags() & Mailbox.Flag.RECENT)!=0   ? "\\Recent "   : "");
818         }
819         static String flags(int flags) {
820             String ret = "(" +
821                 (((flags & Mailbox.Flag.DELETED) == Mailbox.Flag.DELETED) ? "\\Deleted "  : "") +
822                 (((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN)    ? "\\Seen "     : "") +
823                 (((flags & Mailbox.Flag.FLAGGED) == Mailbox.Flag.FLAGGED) ? "\\Flagged "  : "") +
824                 (((flags & Mailbox.Flag.DRAFT) == Mailbox.Flag.DRAFT)   ? "\\Draft "    : "") +
825                 (((flags & Mailbox.Flag.ANSWERED) == Mailbox.Flag.ANSWERED)? "\\Answered " : "") +
826                 (((flags & Mailbox.Flag.RECENT) == Mailbox.Flag.RECENT)  ? "\\Recent "   : "");
827             if (ret.endsWith(" ")) ret = ret.substring(0, ret.length() - 1);
828             return ret + ")";
829         }
830         static String bodystructure(Message m) {
831             // FIXME
832             return "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"ISO-8859-1\") NIL NIL \"7BIT\" "+m.getLength()+" "+m.getNumLines()+")";
833         }
834         static String message(Message m) { return m.toString(); }
835         static String date(Date d) { return "\""+d.toString()+"\""; }
836         static String envelope(Message m) {
837             return
838                 "(" + quotify(m.arrival.toString()) +
839                 " " + quotify(m.subject) +          
840                 " " + addressList(m.from) +      
841                 " " + addressList(m.headers.get("sender")) +
842                 " " + addressList(m.replyto) + 
843                 " " + addressList(m.to) + 
844                 " " + addressList(m.cc) + 
845                 " " + addressList(m.bcc) + 
846                 " " + quotify((String)m.headers.get("in-reply-to")) +
847                 " " + quotify(m.messageid) +
848                 ")";
849         }
850         
851         // FIXME: ugly
852         public static String qq(Stream stream) {
853             StringBuffer sb = new StringBuffer();
854             stream.transcribe(sb);
855             return qq(sb.toString());
856         }
857         public static String qq(String s) {
858             StringBuffer ret = new StringBuffer();
859             ret.append('{');
860             ret.append(s.getBytes().length);
861             ret.append('}');
862             ret.append('\r');
863             ret.append('\n');
864             ret.append(s);
865             return ret.toString();
866         }
867         
868         private static String join(int[] nums) {
869             StringBuffer ret = new StringBuffer();
870             for(int i=0; i<nums.length; i++) {
871                 ret.append(nums[i]);
872                 if (i<nums.length-1) ret.append(' ');
873             }
874             return ret.toString();
875         }
876         private static String join(String delimit, String[] stuff) {
877             StringBuffer ret = new StringBuffer();
878             for(int i=0; i<stuff.length; i++) {
879                 ret.append(stuff[i]);
880                 if (i<stuff.length - 1) ret.append(delimit);
881             }
882             return ret.toString();
883         }
884         }
885
886
887     // Main //////////////////////////////////////////////////////////////////////////////
888
889     public static final int
890         PEEK=0x1, BODYSTRUCTURE=0x2, ENVELOPE=0x4, FLAGS=0x8, INTERNALDATE=0x10, FIELDS=0x800, FIELDSNOT=0x1000,
891         RFC822=0x20, RFC822TEXT=0x40, RFC822SIZE=0x80, HEADERNOT=0x100, UID=0x200, HEADER=0x400;
892
893 }