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