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