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