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