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