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