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