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