bogus
[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.jinetd.Worker;
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 {
36
37     public IMAP() { }
38     public static final float version = (float)0.1;
39
40     // API Class //////////////////////////////////////////////////////////////////////////////
41
42     public static interface Client {
43         public void expunge(int uid);
44         public void list(char separator, String mailbox, boolean lsub, boolean phantom);
45         public void fetch(int num, int flags, int size, Message m, int muid);  // m may be null or incomplete
46     }
47
48     public static interface Server {
49         public String[]  capability();
50         public Hashtable id(Hashtable clientId);
51         public void      copy(Query q, String to);
52         public void      login(String u, String p);
53         public void      logout();
54         public void      unselect();
55         public void      delete(String m);
56         public void      create(String m);
57         public void      append(String m, int flags, Date arrival, String body);
58         public void      check();
59         public void      noop();
60         public void      close();
61         public void      subscribe(String mailbox);
62         public void      unsubscribe(String mailbox);
63         public int       unseen(String mailbox);
64         public int       recent(String mailbox);
65         public int       count(String mailbox);
66         public int       uidNext(String mailbox);
67         public int       uidValidity(String mailbox);
68         public int[]     search(Query q, boolean uid);
69         public void      rename(String from, String to);
70         public void      select(String mailbox, boolean examineOnly);
71         public void      setFlags(Query q, int flags, boolean uid, boolean silent);
72         public void      removeFlags(Query q, int flags, boolean uid, boolean silent);
73         public void      addFlags(Query q, int flags, boolean uid, boolean silent);
74         public void      expunge();
75         public void      fetch(Query q, int spec, String[] headers, int start, int end, boolean uid);
76         public void      lsub(String start, String ref);
77         public void      list(String start, String ref);
78         public static interface Authenticator { public abstract Mailbox authenticate(String user, String pass); } 
79         public static class Exn extends MailException { public Exn(String s) { super(s); } }
80         public static class Bad extends Exn { public Bad(String s) { super(s); } }
81         public static class No extends Exn { public No(String s) { super(s); } }
82     }
83
84
85     // MailboxWrapper //////////////////////////////////////////////////////////////////////////////
86
87     /** wraps an IMAP.Server interface around a Mailbox */
88     public static class MailboxWrapper implements Server {
89
90         public static final char sep = '.';
91
92         Mailbox inbox = null;
93         Mailbox selected = null;
94         Mailbox root = null;
95         Mailbox selected() { if (selected == null) throw new Bad("no mailbox selected"); return selected; }
96         final Server.Authenticator auth;
97         final Client client;
98
99         public MailboxWrapper(Server.Authenticator auth, Client c) { this.auth=auth; this.client=c;}
100
101         private Mailbox mailbox(String name, boolean create) {
102             if (name.equalsIgnoreCase("inbox")) return inbox;
103             Mailbox m = root;
104             for(StringTokenizer st = new StringTokenizer(name, sep + ""); st.hasMoreTokens();)
105                 if ((m = m.slash(st.nextToken(), create)) == null) throw new Server.No("no such mailbox " + name);
106             return m;
107         }
108
109         // FEATURE: not accurate when a wildcard and subsequent non-wildcards both match a single component
110         public void lsub(String start, String ref) { list(start, ref, true); }
111         public void list(String start, String ref) { list(start, ref, false); }
112         public void list(String start, String ref, boolean lsub) {
113             if (ref.length() == 0) { client.list(sep, start, lsub, false); return; }
114             while (start.endsWith(""+sep)) start = start.substring(0, start.length() - 1);
115             if (ref.endsWith("%")) ref = ref + sep;
116             String[] children = (start.length() == 0 ? root : mailbox(start, false)).children();
117             for(int i=0; i<children.length; i++) {
118                 String s = children[i], pre = ref, kid = start + (start.length() > 0 ? sep+"" : "") + s;                
119                 boolean phantom = mailbox(kid, false).phantom();
120                 while(true) {
121                     if (pre.length() == 0) {
122                         if (s.length() == 0)       client.list(sep, kid, lsub, phantom);
123                     } else switch(pre.charAt(0)) {
124                         case sep:        if (s.length() == 0) list(kid, pre.substring(1), lsub);                    break;
125                         case '%':        client.list(sep,kid,lsub,phantom);pre=pre.substring(1); s = "";            continue;
126                         case '*':        client.list(sep,kid,lsub,phantom);list(kid,pre,lsub);pre=pre.substring(1); break;
127                         default:         if (s.length()==0)                                                         break;
128                                          if (s.charAt(0) != pre.charAt(0))                                          break;
129                                          s = s.substring(1); pre = pre.substring(1);                                continue;
130                     }
131                     break;
132                 }
133             }
134         }
135
136         public String[] capability() { return new String[] { "IMAP4rev1" , "UNSELECT", "ID" }; }
137         public Hashtable id(Hashtable clientId) {
138             Hashtable response = new Hashtable();
139             response.put("name", IMAP.class.getName());
140             response.put("version", version + "");
141             response.put("os", System.getProperty("os.name", null));
142             response.put("os-version", System.getProperty("os.version", null));
143             response.put("vendor", "none");
144             response.put("support-url", "http://mail.ibex.org/");
145             return response;
146         }   
147
148         public void copy(Query q, String to) { copy(q, mailbox(to, false)); }
149         /*  */ void copy(Query q, Mailbox to) {
150             for(Mailbox.Iterator it=selected().iterator(q);it.next();) to.add(it.cur(), it.flags() | Mailbox.Flag.RECENT); }
151
152         public void login(String u, String p) {
153             if ((root = auth.authenticate(u,p)) == null) throw new No("Login failed.");
154             inbox = mailbox("INBOX", false);  // FEATURE: ??
155         }
156         public void unselect() { selected = null; }
157         public void delete(String m0) { delete(mailbox(m0,false)); }
158         public void delete(Mailbox m) { if (!m.equals(inbox)) m.destroy(false); else throw new Bad("can't delete inbox"); }
159         public void create(String m) { mailbox(m, true); }
160         public void append(String m,int f,Date a,String b) { try {
161             mailbox(m,false).add(new Message(null,null,b,a),f|Mailbox.Flag.RECENT);
162         } catch (Message.Malformed e) { throw new No(e.getMessage()); } }
163         public void check() { }
164         public void noop() { }
165         public void logout() { }
166         public void close() { for(Mailbox.Iterator it=selected().iterator(Query.deleted()); it.next();) it.delete(); }
167         public void expunge() { for(Mailbox.Iterator it = selected().iterator(Query.deleted());it.next();) expunge(it); }
168         public void expunge(Mailbox.Iterator it) { client.expunge(it.uid()); it.delete(); }
169         public void subscribe(String mailbox) { }
170         public void unsubscribe(String mailbox) { }
171         public int unseen(String mailbox)      { return mailbox(mailbox, false).count(Query.not(Query.seen())); }
172         public int recent(String mailbox)      { return mailbox(mailbox, false).count(Query.recent()); }
173         public int count(String mailbox)       { return mailbox(mailbox, false).count(Query.all()); }
174         public int uidNext(String mailbox)     { return mailbox(mailbox, false).uidNext(); }
175         public int uidValidity(String mailbox) { return mailbox(mailbox, false).uidValidity(); }
176         public void select(String mailbox, boolean examineOnly) {
177             selected = mailbox(mailbox, false);
178         }
179
180         public int[] search(Query q, boolean uid) {
181             Vec.Int vec = new Vec.Int();
182             for(Mailbox.Iterator it = selected().iterator(q); it.next();) {
183                 vec.addElement(uid ? it.uid() : it.num());
184                 it.recent(false);
185             }
186             return vec.dump();
187         }
188
189         public void setFlags(Query q, int f, boolean uid, boolean silent)    { doFlags(q, f, uid, 0, silent); }
190         public void addFlags(Query q, int f, boolean uid, boolean silent)    { doFlags(q, f, uid, 1, silent); }
191         public void removeFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, -1, silent); }
192
193         private void doFlags(Query q, int flags, boolean uid, int style, boolean silent) {
194             for(Mailbox.Iterator it = selected().iterator(q);it.next();) {
195                 boolean recent = it.recent();
196                 if (style == -1)     it.removeFlags(flags);
197                 else if (style == 0) it.setFlags(flags);
198                 else if (style == 1) it.addFlags(flags);
199                 it.recent(recent);
200                 // FIXME
201                 //if (!silent) client.fetch(it.num(), it.flags(), -1, null, it.uid());
202             }
203         }            
204         public void rename(String from0, String to) {
205             Mailbox from = mailbox(from0, false);
206             if (from.equals(inbox))                { from.copy(Query.all(), mailbox(to, true)); }
207             else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), mailbox(to, true)); from.destroy(false); }
208             else from.rename(to);
209         }
210         public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid) {
211             for(Mailbox.Iterator it = selected().iterator(q); it.next(); ) {
212                 Message message = ((spec & (BODYSTRUCTURE | ENVELOPE | INTERNALDATE | FIELDS | FIELDSNOT | RFC822 |
213                                             RFC822TEXT | RFC822SIZE | HEADERNOT | HEADER)) != 0) ? it.cur() : null;
214                 int size = message == null ? 0 : message.size();
215                 client.fetch(it.num(), it.flags(), size, message, it.uid());
216                 it.recent(false);
217             }
218         }
219     }
220
221
222     // Single Session Handler //////////////////////////////////////////////////////////////////////////////
223
224     /** takes an IMAP.Server and exposes it to the world as an IMAP server on a TCP socket */
225     public static class Listener implements Worker, Client {
226         String selectedName = null;
227         Mailbox inbox = null, root = null;
228         Server api;
229         Parser parser = null;
230         Connection conn = null;
231         public Listener() { }
232         Parser.Token token() { return parser.token(); }
233         void println(String s) { conn.println(s); }
234         void newline() { parser.newline(); }
235         Query query() { return parser.query(); }
236         public void handleRequest(Connection conn) {
237             this.conn = conn;
238             parser = new Parser(conn);
239             api = new IMAP.MailboxWrapper(new Main.BogusAuthenticator(), this);
240             conn.setTimeout(30 * 60 * 1000);
241             println("* OK " + conn.vhost + " " + IMAP.class.getName() + " IMAP4rev1 [RFC3501] v" + version + " server ready");
242             for(String tag = null;; newline()) try {
243                 conn.flush();
244                 boolean uid = false;
245                 tag = null; Parser.Token tok = token(); if (tok == null) return; tag = tok.astring();
246                 String command = token().atom();
247                 if (command.equalsIgnoreCase("UID")) { uid = true; command = token().atom(); }
248                 int commandKey = ((Integer)commands.get(command.toUpperCase())).intValue();
249                 switch(commandKey) {
250                     case LOGIN:        api.login(token().astring(), token().astring()); break;
251                     case CAPABILITY:   println("* CAPABILITY " + Printer.join(" ", api.capability())); break;
252                     case AUTHENTICATE: throw new Server.No("AUTHENTICATE not supported");
253                     case LOGOUT:       api.logout(); println("* BYE"); conn.close(); return;
254                     case LIST:         api.list(token().q(), token().q()); break;
255                     case LSUB:         api.lsub(token().q(), token().q()); break;
256                     case SUBSCRIBE:    api.subscribe(token().astring()); break;
257                     case UNSUBSCRIBE:  api.unsubscribe(token().astring()); break;
258                     case RENAME:       api.rename(token().astring(), token().astring()); break;
259                     case COPY:         selected(); api.copy(Query.set(uid, token().set()), token().astring()); break;
260                     case DELETE:       api.delete(token().atom()); break;
261                     case CHECK:        selected(); api.check(); break;
262                     case NOOP:         api.noop(); break;
263                     case CLOSE:        selected(); api.close(); break;
264                     case EXPUNGE:      selected(); api.expunge(); break;
265                     case UNSELECT:     selected(); api.unselect(); selected = false; break;
266                     case CREATE:       api.create(token().astring()); break;
267                     case FETCH:        selected(); fetch(Query.set(lastuid=uid, token().set()),
268                                                          lastfetch=token().lx(), 0, 0, 0, uid, 0); break;
269                     case SEARCH:       selected(); println("* SEARCH " + Printer.join(api.search(query(), uid))); break;
270                     case EXAMINE:
271                     case SELECT: {
272                         String mailbox = token().astring();
273                         api.select(mailbox, commandKey==EXAMINE);
274                         println("* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
275                         println("* " + api.count(mailbox)  + " EXISTS");
276                         println("* " + api.recent(mailbox) + " RECENT");
277                         println("* OK [UIDVALIDITY " + api.uidValidity(mailbox) + "] UIDs valid");
278                         println("* OK [UIDNEXT " + api.uidNext(mailbox) + "]");
279                         println("* OK [PERMANENTFLAGS (\\Seen \\Draft \\Answered \\Deleted)]");
280                         selected = true;
281                         break; }
282                     case STATUS: {
283                         String mailbox = token().astring();  // hack for GNUS buggy client
284                         Parser.Token[] list = token().l();
285                         String response = "";
286                         for(int i=0; i<list.length; i++) {
287                             String s = list[i].atom().toUpperCase();
288                             if (i>0) response += " ";
289                             if (s.equals("MESSAGES"))    response += "MESSAGES "    + api.count(mailbox);
290                             if (s.equals("RECENT"))      response += "RECENT "      + api.recent(mailbox);
291                             if (s.equals("UIDNEXT"))     response += "UIDNEXT "     + api.uidNext(mailbox);
292                             if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + api.uidValidity(mailbox);
293                             if (s.equals("UNSEEN"))      response += "UNSEEN "      + api.unseen(mailbox);
294                         }
295                         println("* STATUS " + mailbox + " (" + response + ")");
296                         break;
297                     }
298                     case APPEND: { 
299                         String m = token().astring();
300                         int flags = 0;
301                         Date arrival = new Date();
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, t.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())); Log.warn(this,b);
325             } catch (Server.No n)  { println(tag==null?"* BAD Invalid tag":(tag+" No "  + n.toString())); Log.warn(this,n); }
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 = q == 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 {
491         private Stream stream;
492         public Parser(Stream from) { this.stream = from; }
493         public Token token(String s) { return new Token(s); }
494         protected Query query() {
495             String s = null;
496             boolean not = false;
497             Query q = null;
498             while(true) {
499                 Parser.Token t = token(false);
500                 if (t == null) break;
501                 if (t.type == t.LIST) throw new Server.No("nested queries not yet supported FIXME");
502                 else if (t.type == t.SET) return Query.num(t.set());
503                 s = t.atom().toUpperCase();
504                 if (s.equals("NOT")) { not = true; continue; }
505                 if (s.equals("OR"))    return Query.or(query(), query());    // FIXME parse rest of list
506                 if (s.equals("AND"))   return Query.and(query(), query());
507             }
508             if (s.startsWith("UN"))        { not = true; s = s.substring(2); }
509             if (s.equals("ANSWERED"))        q = Query.answered();
510             else if (s.equals("DELETED"))    q = Query.deleted();
511             else if (s.equals("ALL"))        q = Query.all();
512             else if (s.equals("DRAFT"))      q = Query.draft();
513             else if (s.equals("FLAGGED"))    q = Query.flagged();
514             else if (s.equals("RECENT"))     q = Query.recent();
515             else if (s.equals("SEEN"))       q = Query.seen();
516             else if (s.equals("OLD"))      { not = true; q = Query.recent(); }
517             else if (s.equals("NEW"))        q = Query.and(Query.recent(), Query.not(Query.seen()));
518             else if (s.equals("KEYWORD"))    q = Query.header("keyword", token().flag());
519             else if (s.equals("HEADER"))     q = Query.header(token().astring(), token().astring());
520             else if (s.equals("BCC"))        q = Query.header("bcc", token().astring());
521             else if (s.equals("CC"))         q = Query.header("cc", token().astring());
522             else if (s.equals("FROM"))       q = Query.header("from", token().astring());
523             else if (s.equals("TO"))         q = Query.header("to", token().astring());
524             else if (s.equals("SUBJECT"))    q = Query.header("subject", token().astring());
525             else if (s.equals("LARGER"))     q = Query.size(token().n(), Integer.MAX_VALUE);
526             else if (s.equals("SMALLER"))    q = Query.size(Integer.MIN_VALUE, token().n());
527             else if (s.equals("BODY"))       q = Query.body(token().astring());
528             else if (s.equals("TEXT"))       q = Query.full(token().astring());
529             else if (s.equals("BEFORE"))     q = Query.arrival(new Date(0), token().date());
530             else if (s.equals("SINCE"))      q = Query.arrival(token().date(), new Date(Long.MAX_VALUE));
531             else if (s.equals("ON"))       { Date d = token().date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
532             else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), token().date());
533             else if (s.equals("SENTSINCE"))  q = Query.sent(token().date(), new Date(Long.MAX_VALUE));
534             else if (s.equals("SENTON"))   { Date d = token().date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
535             else if (s.equals("UID"))        q = Query.uid(token().set());
536             return q;
537         }
538
539         private static void bad(String s) { throw new Server.Bad(s); }
540         class Token {
541             public final byte type;
542             private final String s;
543             private final Parser.Token[] l;
544             private final int n;
545             private static final byte NIL = 0, LIST = 1, QUOTED = 2, NUMBER = 3, ATOM = 4, BAREWORD = 5, SET = 6;
546             public Token()                         { this.s = null; n = 0;      l = null; type = NIL; }
547             public Token(String s)                 { this(s, false); }
548             public Token(String s, boolean quoted) { this.s = s;    n = 0;      l = null; type = quoted ? QUOTED : ATOM;  }
549             public Token(Parser.Token[] list)             { this.s = null; n = 0;      l = list; type = LIST; }
550             public Token(int number)               { this.s = null; n = number; l = null; type = NUMBER; }
551
552             public String   flag()    { if (type != ATOM) bad("expected a flag"); return s; }
553             public int      n()       { if (type != NUMBER) bad("expected number"); return n; }
554             public int      nz()      { int n = n(); if (n == 0) bad("expected nonzero number"); return n; }
555             public String   q()       { if (type == NIL) return null; if (type != QUOTED) bad("expected qstring"); return s; }
556             public Parser.Token[]  l()       { if (type == NIL) return null; if (type != LIST) bad("expected list"); return l; }
557             public Parser.Token[]  lx()      {
558                 if (type == LIST) return l;
559                 Vec v = new Vec();
560                 v.addElement(this);
561                 while(true) {
562                     Parser.Token t = token(false);
563                     if (t == null) break;
564                     v.addElement(t);
565                 }
566                 Parser.Token[] ret = new Parser.Token[v.size()];
567                 v.copyInto(ret);
568                 return ret;
569             }
570             public String   nstring() { if (type==NIL) return null; if (type!=QUOTED) bad("expected nstring"); return s; }
571             public String   astring() {
572                 if (type != ATOM && type != QUOTED) bad("expected atom or string");
573                 if (s == null) bad("astring cannot be null");
574                 return s; }
575             public String[] sl() {
576                 if (type == NIL) return null;
577                 if (type != LIST) bad("expected list");
578                 String[] ret = new String[l.length];
579                 for(int i=0; i<ret.length; i++) ret[i] = l[i].s;
580                 return ret;
581             }
582             public int flags() {
583                 if (type != LIST) bad("expected flag list");
584                 int ret = 0;
585                 for(int i=0; i<l.length; i++) {
586                     String flag = l[i].s;
587                     if (flag.equals("\\Deleted"))       ret |= Mailbox.Flag.DELETED;
588                     else if (flag.equals("\\Seen"))     ret |= Mailbox.Flag.SEEN;
589                     else if (flag.equals("\\Flagged"))  ret |= Mailbox.Flag.FLAGGED;
590                     else if (flag.equals("\\Draft"))    ret |= Mailbox.Flag.DRAFT;
591                     else if (flag.equals("\\Answered")) ret |= Mailbox.Flag.ANSWERED;
592                     else if (flag.equals("\\Recent"))   ret |= Mailbox.Flag.RECENT;
593                 }
594                 return ret;
595             }
596             public int[] set() {
597                 if (type != ATOM) bad("expected a messageid set");
598                 Vec.Int ids = new Vec.Int();
599                 StringTokenizer st = new StringTokenizer(s, ",");
600                 while(st.hasMoreTokens()) {
601                     String s = st.nextToken();
602                     if (s.indexOf(':') == -1) {
603                         if (s.equals("*")) {
604                             ids.addElement(0);
605                             ids.addElement(Integer.MAX_VALUE);
606                         } else {
607                             ids.addElement(Integer.parseInt(s));
608                             ids.addElement(Integer.parseInt(s));
609                         }
610                         continue; }
611                     int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
612                     String end_s = s.substring(s.indexOf(':')+1);
613                     if (end_s.equals("*")) { ids.addElement(start); ids.addElement(Integer.MAX_VALUE); }
614                     else {
615                         int end = Integer.parseInt(end_s);
616                         for(int j=Math.min(start,end); j<=Math.max(start,end); j++) {
617                             ids.addElement(j);
618                             ids.addElement(j);
619                         }
620                     }
621                 }
622                 return ids.dump();
623             }
624             public Date date() {
625                 if (type != QUOTED && type != ATOM) bad("Expected quoted or unquoted date");
626                 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
627                 } catch (ParseException p) { throw new Server.Bad("invalid date format; " + p); }
628             }
629             public Date datetime() {
630                 if (type != QUOTED) bad("Expected quoted datetime");
631                 try { return new SimpleDateFormat("dd-MM-yyyy hh:mm:ss zzzz").parse(s.trim());
632                 } catch (ParseException p) { throw new Server.Bad("invalid datetime format " + s + " : " + p); }
633             }
634             public String atom() {
635                 if (type != ATOM) bad("expected atom");
636                 for(int i=0; i<s.length(); i++) {
637                     char c = s.charAt(i);
638                     if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*' || c == '\"' | c == '\\')
639                         bad("invalid char in atom: " + c);
640                 }
641                 return s;
642             }
643         }
644
645         public void newline() {
646             while (stream.peekc() == '\r' || stream.peekc() == '\n' || stream.peekc() == ' ') {
647                 for(char c = stream.peekc(); c == ' ';) { stream.getc(); c = stream.peekc(); };
648                 for(char c = stream.peekc(); c == '\r' || c == '\n';) { stream.getc(); c = stream.peekc(); };
649             }
650         }
651
652         public Token token() { return token(true); }
653         public Token token(boolean freak) {
654             Vec toks = new Vec();
655             StringBuffer sb = new StringBuffer();
656             char c = stream.getc(); while (c == ' ') c = stream.getc();
657             if (c == '\r' || c == '\n') { if (freak) bad("unexpected end of line"); return null; }
658             else if (c == '{') {
659                 while(stream.peekc() != '}') sb.append(stream.getc());
660                 stream.getc();
661                 stream.println("+ Ready when you are...");
662                 int octets = Integer.parseInt(sb.toString());
663                 while(stream.peekc() == ' ') stream.getc();   // whitespace
664                 while(stream.peekc() == '\n' || stream.peekc() == '\r') stream.getc();
665                 byte[] bytes = new byte[octets];
666                 int numread = 0;
667                 while(numread < bytes.length) {
668                     int n = stream.read(bytes, numread, bytes.length - numread);
669                     if (n == -1) bad("end of stream while reading IMAP qstring");
670                     numread += n;
671                 }
672                 return new Token(new String(bytes), true);
673             } else if (c == '\"') {
674                 while(true) {
675                     c = stream.getc();
676                     if (c == '\\') sb.append(stream.getc());
677                     else if (c == '\"') break;
678                     else sb.append(c);
679                 }
680                 return new Token(sb.toString(), true);
681                 
682                 // NOTE: this is technically a violation of the IMAP grammar, since atoms like FOO[BAR should be legal
683             } else if (c == ']' || c == ')') { return null;
684             } else if (c == '[' || c == '(') {
685                 Token t;
686                 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
687                 Token[] ret = new Token[toks.size()];
688                 toks.copyInto(ret);
689                 return new Token(ret);
690                 
691             } else while(true) {
692                 sb.append(c);
693                 c = stream.peekc();
694                 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '[' || c == ']' ||
695                     c == '{' || c == '\n' || c == '\r')
696                     return new Token(sb.toString(), false);
697                 stream.getc();
698             }
699         }
700     }
701     
702     public static class Printer {
703             static String quotify(String s){
704                 return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
705             static String quotify(Date d) {
706                 return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
707             static String address(Address a) {
708                 return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
709             public static String addressList(Object a) {
710                 if (a == null) return "NIL";
711                 if (a instanceof Address) return "("+address((Address)a)+")";
712                 Address[] aa = (Address[])a;
713                 StringBuffer ret = new StringBuffer();
714                 ret.append("(");
715                 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
716                 ret.append(")");
717                 return ret.toString();
718             }
719             static String flags(Mailbox.Iterator it) {
720                 return
721                     (it.deleted()  ? "\\Deleted "  : "") +
722                     (it.seen()     ? "\\Seen "     : "") +
723                     (it.flagged()  ? "\\Flagged "  : "") +
724                     (it.draft()    ? "\\Draft "    : "") +
725                     (it.answered() ? "\\Answered " : "") +
726                     (it.recent()   ? "\\Recent "   : "");
727         }
728         static String flags(int flags) {
729             String ret = "(" +
730                 (((flags & Mailbox.Flag.DELETED) == Mailbox.Flag.DELETED) ? "\\Deleted "  : "") +
731                 (((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN)    ? "\\Seen "     : "") +
732                 (((flags & Mailbox.Flag.FLAGGED) == Mailbox.Flag.FLAGGED) ? "\\Flagged "  : "") +
733                 (((flags & Mailbox.Flag.DRAFT) == Mailbox.Flag.DRAFT)   ? "\\Draft "    : "") +
734                 (((flags & Mailbox.Flag.ANSWERED) == Mailbox.Flag.ANSWERED)? "\\Answered " : "") +
735                 (((flags & Mailbox.Flag.RECENT) == Mailbox.Flag.RECENT)  ? "\\Recent "   : "");
736             if (ret.endsWith(" ")) ret = ret.substring(0, ret.length() - 1);
737             return ret + ")";
738         }
739         static String bodystructure(Message m) {
740             // FIXME
741             return "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"ISO-8859-1\") NIL NIL \"7BIT\" "+m.size()+" "+m.lines+")";
742         }
743         static String message(Message m) { return m.toString(); }
744         static String date(Date d) { return d.toString(); }
745         static String envelope(Message m) {
746             return
747                 "(" + quotify(m.arrival.toString()) +
748                 " " + quotify(m.subject) +          
749                 " " + addressList(m.from) +      
750                 " " + addressList(m.headers.get("sender")) +
751                 " " + addressList(m.replyto) + 
752                 " " + addressList(m.to) + 
753                 " " + addressList(m.cc) + 
754                 " " + addressList(m.bcc) + 
755                 " " + quotify((String)m.headers.get("in-reply-to")) +
756                 " " + quotify(m.messageid) +
757                 ")";
758         }
759         
760         public static String qq(String s) {
761             StringBuffer ret = new StringBuffer();
762             ret.append('{');
763             ret.append(s.length());
764             ret.append('}');
765             ret.append('\r');
766             ret.append('\n');
767             ret.append(s);
768             return ret.toString();
769         }
770         
771         private static String join(int[] nums) {
772             StringBuffer ret = new StringBuffer();
773             for(int i=0; i<nums.length; i++) {
774                 ret.append(nums[i]);
775                 if (i<nums.length-1) ret.append(' ');
776             }
777             return ret.toString();
778         }
779         private static String join(String delimit, String[] stuff) {
780             StringBuffer ret = new StringBuffer();
781             for(int i=0; i<stuff.length; i++) {
782                 ret.append(stuff[i]);
783                 if (i<stuff.length - 1) ret.append(delimit);
784             }
785             return ret.toString();
786         }
787         }
788
789
790     // Main //////////////////////////////////////////////////////////////////////////////
791
792     /** simple listener for testing purposes */
793     public static void main(String[] args) throws Exception {
794         ServerSocket ss = new ServerSocket(143);
795         for(;;) {
796             final Socket s = ss.accept();
797             new Thread() { public void run() { try {
798                 final Mailbox root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT+File.separatorChar+"imap", true);
799                 new Listener();
800             } catch (Exception e) { e.printStackTrace(); } } }.start();
801         }
802     }
803
804     public static final int
805         PEEK=0x1, BODYSTRUCTURE=0x2, ENVELOPE=0x4, FLAGS=0x8, INTERNALDATE=0x10, FIELDS=0x800, FIELDSNOT=0x1000,
806         RFC822=0x20, RFC822TEXT=0x40, RFC822SIZE=0x80, HEADERNOT=0x100, UID=0x200, HEADER=0x400;
807 }