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