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