append sorta works; dates are broken
[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 // FEATURE: hoist all the ok()'s?
11 // FEATURE: pipelining
12 // FEATURE: support [charset]
13 public class IMAP extends MessageProtocol {
14
15     public static final char imapSeparator = '.';
16
17     public static void main(String[] args) throws Exception {
18         ServerSocket ss = new ServerSocket(143);
19         while(true) {
20             System.out.println("listening");
21             final Socket s = ss.accept();
22             System.out.println("connected");
23             new Thread() {
24                 public void run() {
25                     try {
26                         Mailbox root =
27                             FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT + File.separatorChar + "imap", true);
28                         Mailbox inbox = root.slash("users", true).slash("megacz", true);
29                         new Listener(s, "megacz.com", root, inbox).handleRequest();
30                     } catch (Exception e) {
31                         e.printStackTrace();
32                     }
33                 }
34             }.start();
35         }
36     }
37
38     public static class Exn extends MailException {
39         public Exn(String s) { super(s); }
40         public static class No extends Exn { public No(String s) { super(s); } }
41         public static class Bad extends Exn { public Bad(String s) { super(s); } }
42     }
43
44     private static class Listener extends Incoming {
45         Mailbox selected = null;
46         Mailbox root;
47         Mailbox inbox;
48         Socket conn;
49         String vhost;
50         PrintWriter pw;
51         InputStream is;
52         PushbackReader r;
53         public void init() { }
54         public Listener(Socket conn, String vhost, Mailbox root, Mailbox inbox) throws IOException {
55             this.vhost = vhost;
56             this.conn = conn;
57             this.selected = null;
58             this.root = root;
59             this.inbox = inbox;
60             this.pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
61             this.is = conn.getInputStream();
62             this.r = new PushbackReader(new InputStreamReader(is));
63         }
64
65         private void star(String s) {
66             pw.println("* " + s);
67             System.err.println("* " + s);
68             pw.flush();
69         }
70
71         // FIXME: user-inbox-relative stuff
72         // FIXME should throw a No if mailbox not found and create==false
73         private Mailbox getMailbox(String name, boolean create) {
74             Mailbox m = root;
75             while(name.length() > 0) {
76                 int end = name.length();
77                 if (name.indexOf(imapSeparator) != -1) end = name.indexOf(imapSeparator);
78                 m = m.slash(name.substring(0, end), create);
79                 if (end == name.length()) break;
80                 name = name.substring(end+1);
81             }
82             return m;
83         }
84
85         private boolean auth(String user, String pass) { /* FEATURE */ return user.equals("megacz") && pass.equals("pass"); }
86
87         // FEATURE: manage subscriptions
88         public void lsub(Mailbox m, String s) {
89             star("LSUB () \".\" INBOX");
90         }
91
92         // FIXME
93         public void list(Mailbox m, String s) {
94             //star("LIST () \".\" INBOX");
95             star("LIST () \".\" users.megacz.imap");
96         }
97
98         public void copy(final Query q, Mailbox to) { for(Mailbox.Iterator it=selected.iterator(q);it.next();) to.add(it.cur()); }
99         public void login(String user, String pass) { if (!auth(user, pass)) throw new Exn.No("Liar, liar, pants on fire."); }
100         public void capability() { star("CAPABILITY IMAP4rev1"); }
101         public void logout() { star("BYE LOGOUT received"); }
102         public void delete(Mailbox m) { if (!m.equals(inbox)) m.destroy(); }
103         public void create(String mailbox){if(!mailbox.endsWith(".")&&!mailbox.equalsIgnoreCase("inbox"))getMailbox(mailbox,true);}
104         public void close(boolean examineOnly) { expunge(false, true); selected = null; }
105         public void check() { }
106         public void noop() { }
107
108         public void rename(Mailbox from, String to) {
109             if (from.equals(inbox))                from.copy(Query.all(), getMailbox(to, true));
110             else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), getMailbox(to, true)); from.destroy(); }
111             else from.rename(to);
112         }
113
114         public void status(final Mailbox m, Token[] attrs) {
115             int count0 = 0, count1 = 0, count2 = 0;
116             for(Mailbox.Iterator it = m.iterator(); it.next(); ) { if (!it.seen()) count0++; if (it.recent()) count1++; count2++; }
117             String response = "";
118             for(int i=0; i<attrs.length; i++) {
119                 String s = attrs[i].atom();
120                 if (s.equals("MESSAGES"))    response += "MESSAGES "    + count2;
121                 if (s.equals("RECENT"))      response += "RECENT "      + count0;
122                 if (s.equals("UIDNEXT"))     response += "UNSEEN "      + count1;
123                 if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + m.uidValidity();
124                 if (s.equals("UNSEEN"))      response += "UIDNEXT "     + m.uidNext();
125             }
126             star("STATUS " + /* FIXME m.getName() +*/ " (" + response + ")");
127         }
128
129         public void select(String mailbox, boolean examineOnly) {
130             selected = getMailbox(mailbox, false);
131             if (selected == null) throw new Exn.No("no such mailbox");  // should this be 'Bad'?
132             star(selected.count(Query.all()) + " EXISTS");
133             star(selected.count(Query.recent()) + " RECENT");
134             //star("OK [UNSEEN 12] Message 12 is first unseen");    FEATURE
135             star("OK [UIDVALIDITY " + selected.uidValidity() + "] UIDs valid");
136             star("FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
137             // FEATURE: READ-WRITE / READ-ONLY
138         }
139
140         public void expunge(final boolean examineOnly, final boolean silent) {
141             if (selected == null) throw new Exn.Bad("no mailbox selected");
142             for(Mailbox.Iterator it = selected.iterator(); it.next();) {
143                 if (!it.deleted()) return;
144                 if (!silent) star(it.uid() + " EXPUNGE");
145                 if (!examineOnly) it.delete();
146             }
147         }
148
149         public void append(Mailbox m, Token t) {
150             Token[] flags = null;
151             Date arrival = null;
152             if (t.type == t.LIST)   { flags = t.l();          t = token(); }
153             if (t.type == t.QUOTED) { arrival = t.datetime(); t = token(); }
154             String literal = q();
155             m.add(new Message(null, new Address[] { null }, new LineReader(new StringReader(literal))));
156             if (flags != null) { /* FEATURE */ }
157         }
158
159         public void fetch(Query q, Token t) {
160             Token[] tl = null;
161             int start = -1, end = -1;
162             boolean peek = false, fast = false, all = false, full = false;
163             if (t.type == Token.LIST) tl = t.l();
164             else if (t.atom().equals("FULL")) full = true;
165             else if (t.atom().equals("ALL")) all = true;
166             else if (t.atom().equals("FAST")) fast = true;
167             StringBuffer reply = new StringBuffer();
168             for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
169                 Message m = it.cur();
170                 for (int i=0; i<tl.length; i++) {
171                     String s = tl[i].atom();
172                     if (s.startsWith("BODY.PEEK"))                 { peek = true; s = "BODY" + s.substring(9); }
173                     if (s.startsWith("BODY.1"))                      s = "BODY" + s.substring(6);
174                     if (s.indexOf('<') != -1) {
175                         String range = s.substring(s.indexOf('<') + 1, s.indexOf('>'));
176                         s = s.substring(0, s.indexOf('<'));
177                         if (range.indexOf(imapSeparator) == -1) end = Integer.MAX_VALUE;
178                         else {
179                             end = Integer.parseInt(range.substring(range.indexOf(imapSeparator) + 1));
180                             range = range.substring(0, range.indexOf(imapSeparator));
181                         }
182                         start = Integer.parseInt(range);
183                     }
184                     if (s.equals("ENVELOPE") || all || full)          reply.append("ENVELOPE " + envelope(m) + " ");
185                     if (s.equals("FLAGS") || full || all || fast)  reply.append("FLAGS (" + flags(it) + ") ");
186                     if (s.equals("INTERNALDATE") || full || all || fast) reply.append("INTERNALDATE "+quotify(m.arrival)+" ");
187                     if (s.equals("RFC822.SIZE") || full || all || fast) reply.append("RFC822.SIZE " + m.rfc822size() + " ");
188                     if (s.equals("RFC822.HEADER") || s.equals("BODY[HEADER]"))
189                         { reply.append("BODY[HEADER] {" + m.allHeaders.length() + "}\r\n"); reply.append(m.allHeaders); }
190                     if (s.equals("RFC822")||s.equals("RFC822.TEXT")||s.equals("BODY")||s.equals("BODY[]")||s.equals("TEXT")||full)
191                         { reply.append("BODY[TEXT] {" + m.body.length() + "}\r\n"); reply.append(m.body); }
192                     if (s.equals("UID"))                        reply.append("UID " + it.uid());
193                     if (s.equals("MIME"))                       throw new Exn.No("FETCH BODY.MIME not supported");
194                     if (s.startsWith("BODY[HEADER.FIELDS"))     throw new Exn.No("partial headers not supported");
195                     if (s.startsWith("BODY[HEADER.FIELDS.NOT")) throw new Exn.No("partial headers not supported");
196                     if (s.equals("BODYSTRUCTURE"))
197                         reply.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " +
198                                      m.rfc822size()+" "+ m.lines +")");
199                 }
200                 star(it.num() + " FETCH (" + reply.toString() + ")");
201                 // FEATURE: range requests
202                 // FEATURE set seen flag if not BODY.PEEK
203             }
204         }
205
206         // FEATURE: hoist the parsing here
207         public void store(Query q, String what, Token[] flags) {
208             for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
209                 Message m = it.cur();
210                 if (what.charAt(0) == 'F') {
211                     it.deleted(false); it.seen(false); it.flagged(false); it.draft(false); it.answered(false); it.recent(false); }
212                 for(int j=0; j<flags.length; j++) {
213                     String flag = flags[j].flag();
214                     if (flag.equals("Deleted"))  it.deleted(what.charAt(0) != '-');
215                     if (flag.equals("Seen"))     it.seen(what.charAt(0) != '-');
216                     if (flag.equals("Flagged"))  it.flagged(what.charAt(0) != '-');
217                     if (flag.equals("Draft"))    it.draft(what.charAt(0) != '-');
218                     if (flag.equals("Answered")) it.answered(what.charAt(0) != '-');
219                     if (flag.equals("Recent"))   it.recent( what.charAt(0) != '-');
220                 }
221                 selected.add(m);  // re-add (?)
222             }
223         }
224
225         public boolean handleRequest() throws IOException {
226             pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
227             System.err.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
228             pw.flush();
229             while(true) {
230                 String tag = null;
231                 try {
232                     boolean uid = false;
233                     tag = null;
234                     // FIXME better error if atom() fails
235                     tag = atom();
236                     String command = atom();
237                     if (command.equalsIgnoreCase("UID"))             { uid = true; command = atom(); }
238                     if (command.equalsIgnoreCase("AUTHENTICATE"))    { login(astring(), astring()); }
239                     else if (command.equalsIgnoreCase("LIST"))         list(mailbox(), mailboxPattern()); 
240                     else if (command.equalsIgnoreCase("LSUB"))         lsub(mailbox(), mailboxPattern()); 
241                     else if (command.equalsIgnoreCase("CAPABILITY")) { capability(); }
242                     else if (command.equalsIgnoreCase("LOGIN"))        login(astring(), astring());
243                     else if (command.equalsIgnoreCase("LOGOUT"))     { logout(); conn.close(); return false; }
244                     else if (command.equalsIgnoreCase("RENAME"))       rename(mailbox(), atom());
245                     else if (command.equalsIgnoreCase("APPEND"))       append(mailbox(), token());
246                     else if (command.equalsIgnoreCase("EXAMINE"))      select(astring(), true);
247                     else if (command.equalsIgnoreCase("SELECT"))       select(astring(), false);
248                     else if (command.equalsIgnoreCase("COPY"))         copy(Query.num(set()), mailbox());
249                     else if (command.equalsIgnoreCase("DELETE"))       delete(mailbox());
250                     else if (command.equalsIgnoreCase("CHECK"))        check();
251                     else if (command.equalsIgnoreCase("NOOP"))         noop();
252                     else if (command.equalsIgnoreCase("CREATE"))       create(astring());
253                     else if (command.equalsIgnoreCase("STORE"))        store(Query.num(set()), atom(), l());
254                     else if (command.equalsIgnoreCase("FETCH"))        fetch(Query.num(set()), token());
255                     else if (command.equalsIgnoreCase("STATUS"))       status(mailbox(), l());
256                     else                                     throw new Exn.Bad("unrecognized command \"" + command + "\"");
257                     pw.println(tag + " OK " + command + " Completed.");
258                     System.err.println(tag + " OK " + command + " Completed.");
259                 } catch (Exn.Bad b) { pw.println(tag + " Bad " + b.toString()); System.err.println(tag + " Bad " + b.toString()); b.printStackTrace();
260                 } catch (Exn.No n) {  pw.println(tag + " OK " + n.toString()); System.err.println(tag + " OK " + n.toString());
261                 }
262                 pw.flush();
263                 newline();
264             }
265         }
266
267         
268         // Unparsing (printing) logic //////////////////////////////////////////////////////////////////////////////
269
270         static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
271         static String quotify(Date d) { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
272         static String address(Address a) {return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
273         public static String addressList(Object a) {
274             if (a == null) return "NIL";
275             if (a instanceof Address) return "("+address((Address)a)+")";
276             Address[] aa = (Address[])a;
277             StringBuffer ret = new StringBuffer();
278             ret.append("(");
279             for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
280             ret.append(")");
281             return ret.toString();
282         }
283         static String flags(Mailbox.Iterator it) {
284             return 
285                 (it.deleted()  ? "\\Deleted "  : "") +
286                 (it.seen()     ? "\\Seen "     : "") +
287                 (it.flagged()  ? "\\Flagged "  : "") +
288                 (it.draft()    ? "\\Draft "    : "") +
289                 (it.answered() ? "\\Answered " : "") +
290                 (it.recent()   ? "\\Recent "   : "");
291         }
292         static String envelope(Message m) {
293             return
294                 "(" + quotify(m.arrival.toString()) +
295                 " " + quotify(m.subject) +          
296                 " " + addressList(m.from) +      
297                 " " + addressList(m.headers.get("sender")) +
298                 " " + addressList(m.replyto) + 
299                 " " + addressList(m.to) + 
300                 " " + addressList(m.cc) + 
301                 " " + addressList(m.bcc) + 
302                 " " + quotify((String)m.headers.get("in-reply-to")) +
303                 " " + quotify(m.messageid) +
304                 ")";
305         }
306
307
308
309         // Parsing Logic //////////////////////////////////////////////////////////////////////////////
310
311         Query query() {
312             String s = null;
313             boolean not = false;
314             Query q = null;
315             while(true) {
316                 Token t = token();
317                 if (t.type == t.LIST) throw new Exn.No("nested queries not yet supported");
318                 else if (t.type == t.SET) return Query.num(t.set());
319                 s = t.atom();
320                 if (s.equals("NOT")) { not = true; continue; }
321                 if (s.equals("OR"))    return Query.or(query(), query());
322                 if (s.equals("AND"))   return Query.and(query(), query());
323                 break;
324             }
325             if (s.startsWith("UN"))        { not = true; s = s.substring(2); }
326             if (s.equals("ANSWERED"))        q = Query.answered();
327             else if (s.equals("DELETED"))    q = Query.deleted();
328             else if (s.equals("DRAFT"))      q = Query.draft();
329             else if (s.equals("FLAGGED"))    q = Query.flagged();
330             else if (s.equals("RECENT"))     q = Query.recent();
331             else if (s.equals("SEEN"))       q = Query.seen();
332             else if (s.equals("OLD"))      { not = true; q = Query.recent(); }
333             else if (s.equals("NEW"))        q = Query.and(Query.recent(), Query.not(Query.seen()));
334             else if (s.equals("KEYWORD"))    q = Query.header("keyword", flag());
335             else if (s.equals("HEADER"))     q = Query.header(astring(), astring());
336             else if (s.equals("BCC"))        q = Query.header("bcc", astring());
337             else if (s.equals("CC"))         q = Query.header("cc", astring());
338             else if (s.equals("FROM"))       q = Query.header("from", astring());
339             else if (s.equals("TO"))         q = Query.header("to", astring());
340             else if (s.equals("SUBJECT"))    q = Query.header("subject", astring());
341             else if (s.equals("LARGER"))     q = Query.size(n(), Integer.MAX_VALUE);
342             else if (s.equals("SMALLER"))    q = Query.size(Integer.MIN_VALUE, n());
343             else if (s.equals("BODY"))       q = Query.body(astring());
344             else if (s.equals("TEXT"))       q = Query.full(astring());
345             else if (s.equals("BEFORE"))     q = Query.arrival(new Date(0), date());
346             else if (s.equals("SINCE"))      q = Query.arrival(date(), new Date(Long.MAX_VALUE));
347             else if (s.equals("ON"))       { Date d = date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
348             else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), date());
349             else if (s.equals("SENTSINCE"))  q = Query.sent(date(), new Date(Long.MAX_VALUE));
350             else if (s.equals("SENTON"))   { Date d = date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
351             else if (s.equals("UID"))        q = Query.uid(set());
352             return q;
353         }
354
355         class Token {
356             private byte type;
357             private final String s;
358             private final Token[] l;
359             private final int n;
360             private static final byte NIL = 0;
361             private static final byte LIST = 1;
362             private static final byte QUOTED = 2;
363             private static final byte NUMBER = 3;
364             private static final byte ATOM = 4;
365             private static final byte BAREWORD = 5;
366             private static final byte SET = 6;
367             public Token() { n = 0; l = null; s = null; type = NIL; }
368             public Token(String s, boolean quoted) { this.s = s; l = null; type = quoted ? QUOTED : ATOM; n = 0; }
369             public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
370             public Token(int number) { n = number; l = null; s = null; type = NUMBER; }
371
372             public String mailboxPattern() throws Exn.Bad {
373                 if (type == ATOM) return s;
374                 if (type == QUOTED) return s;
375                 throw new Exn.Bad("exepected a mailbox pattern");            
376             }
377             public String flag() throws Exn.Bad {
378                 if (type != ATOM) throw new Exn.Bad("expected a flag");
379                 return s;  // if first char != backslash, it is a keyword-flag
380             }
381             public int n() throws Exn.Bad {
382                 if (type != NUMBER) throw new Exn.Bad("expected number");
383                 return n;
384             }
385             public int nz() throws Exn.Bad {
386                 if (type != NUMBER) throw new Exn.Bad("expected number");
387                 if (n == 0) throw new Exn.Bad("expected nonzero number");
388                 return n;
389             }
390             public String  q() throws Exn.Bad {
391                 if (type == NIL) return null;
392                 if (type != QUOTED) throw new Exn.Bad("expected qstring");
393                 return s;
394             }
395             public Token[] l() throws Exn.Bad {
396                 if (type == NIL) return null;
397                 if (type != LIST) throw new Exn.Bad("expected parenthesized list");
398                 return l;
399             }
400             public int[] set() throws Exn.Bad {
401                 if (type != ATOM) throw new Exn.Bad("expected a messageid set");
402                 Vec ids = new Vec();
403                 StringTokenizer st = new StringTokenizer(s, ",");
404                 while(st.hasMoreTokens()) {
405                     String s = st.nextToken();
406                     if (s.indexOf(':') != -1) {
407                         int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
408                         String end_s = s.substring(s.indexOf(':')+1);
409                         if (end_s.equals("*")) {
410                             ids.addElement(new Integer(start));
411                             ids.addElement(new Integer(-1));
412                         } else {
413                             int end = Integer.parseInt(end_s);
414                             for(int j=start; j<=end; j++) ids.addElement(new Integer(j));
415                         }
416                     } else {
417                         ids.addElement(new Integer(Integer.parseInt(s)));
418                     }
419                 }
420                 int[] ret = new int[ids.size()];
421                 for(int i=0; i<ret.length; i++) ret[i] = ((Integer)ids.elementAt(i)).intValue();
422                 return ret;
423             }
424             public Date date() throws Exn.Bad {
425                 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted date");
426                 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
427                 } catch (ParseException p) { throw new Exn.Bad("invalid date format; " + p); }
428             }
429             public Date datetime() throws Exn.Bad {
430                 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted datetime");
431                 try { return new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").parse(s.trim());
432                 } catch (ParseException p) { throw new Exn.Bad("invalid datetime format " + s + " : " + p); }
433             }
434             public String nstring() throws Exn.Bad {
435                 if (type == NIL) return null;
436                 if (type == QUOTED) return s;
437                 throw new Exn.Bad("expected NIL or string");
438             }
439             public String astring() throws Exn.Bad {
440                 if (type == ATOM) return s;
441                 if (type == QUOTED) return s;
442                 throw new Exn.Bad("expected atom or string");
443             }
444             public String atom() throws Exn.Bad {
445                 if (type != ATOM) throw new Exn.Bad("expected atom");
446                 for(int i=0; i<s.length(); i++) {
447                     char c = s.charAt(i);
448                     if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*')
449                         throw new Exn.Bad("invalid char in atom: " + c);
450                 }
451                 return s;
452             }
453             public Mailbox mailbox() throws Exn.Bad {
454                 if (type == BAREWORD && s.toLowerCase().equals("inbox")) return getMailbox("INBOX", false);
455                 return getMailbox(astring(), false);
456             }
457
458         }
459
460         public char getc() throws IOException {
461             int ret = r.read();
462             if (ret == -1) throw new EOFException();
463             System.err.print((char)ret);
464             System.err.flush();
465             return (char)ret;
466         }
467         public  char peekc() throws IOException {
468             int ret = r.read();
469             if (ret == -1) throw new EOFException();
470             r.unread(ret);
471             return (char)ret;
472         }
473         public  void fill(byte[] b) throws IOException {
474             int num = 0;
475             while (num < b.length) {
476                 int numread = is.read(b, num, b.length - num);
477                 if (numread == -1) throw new EOFException();
478                 num += numread;
479             }
480         }
481
482         public void newline() {
483             try {
484                 for(char c = peekc(); c == ' ';) { getc(); c = peekc(); };
485                 for(char c = peekc(); c == '\r' || c == '\n';) { getc(); c = peekc(); };
486             } catch (IOException e) {
487                 e.printStackTrace();
488             }
489         }
490
491         public Token token() {
492             try {
493                 Vec toks = new Vec();
494                 StringBuffer sb = new StringBuffer();
495                 char c = getc(); while (c == ' ') c = getc();
496                 if (c == '\r' || c == '\n') {
497                     throw new Exn.Bad("unexpected end of line");
498                 } if (c == '{') {
499                     while(peekc() != '}') sb.append(getc());
500                     int octets = Integer.parseInt(sb.toString());
501                     while(peekc() == ' ') getc();   // whitespace
502                     while (getc() != '\n' && getc() != '\r') { }
503                     byte[] bytes = new byte[octets];
504                     fill(bytes);
505                     return new Token(new String(bytes), true);
506                 } else if (c == '\"') {
507                     while(true) {
508                         c = getc();
509                         if (c == '\\') sb.append(getc());
510                         else if (c == '\"') break;
511                         else sb.append(c);
512                     }
513                     return new Token(sb.toString(), true);
514                 } else if (c == ')') {
515                     return null;
516                 } else if (c == '(') {
517                     Token t;
518                     do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
519                     Token[] ret = new Token[toks.size()];
520                     toks.copyInto(ret);
521                     return null;  // FIXME
522                 } else while(true) {
523                     sb.append(c);
524                     c = peekc();
525                     if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '{' || c == '\n' || c == '\r')
526                         return new Token(sb.toString(), false);
527                     getc();
528                 }
529             } catch (IOException e) {
530                 e.printStackTrace();
531                 return null;
532             }
533         }
534
535         // FEATURE: inline these?
536         public String mailboxPattern() throws Exn.Bad { return token().mailboxPattern(); }
537         public String flag() throws Exn.Bad { return token().flag(); }
538         public int n() throws Exn.Bad { return token().n(); }
539         public int nz() throws Exn.Bad { return token().nz(); }
540         public String  q() throws Exn.Bad { return token().q(); }
541         public Token[] l() throws Exn.Bad { return token().l(); }
542         public int[] set() throws Exn.Bad { return token().set(); }
543         public Date date() throws Exn.Bad { return token().date(); }
544         public Date datetime() throws Exn.Bad { return token().datetime(); }
545         public String nstring() throws Exn.Bad { return token().nstring(); }
546         public String astring() throws Exn.Bad { return token().astring(); }
547         public String atom() throws Exn.Bad { return token().atom(); }
548         public Mailbox mailbox() throws Exn.Bad, IOException { return token().mailbox(); }
549     }
550 }