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