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