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