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