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