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