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