lotsa stuff works
[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 == null) { tl = new Token[] { new Token("BODY", false) }; }
164             else if (t.type == Token.LIST) tl = t.l();
165             else if (t.atom().equals("FULL")) full = true;
166             else if (t.atom().equals("ALL")) all = true;
167             else if (t.atom().equals("FAST")) fast = true;
168             StringBuffer reply = new StringBuffer();
169             for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
170                 Message m = it.cur();
171                 for (int i=0; i<tl.length; i++) {
172                     String s = tl[i].atom();
173                     if (s.startsWith("BODY.PEEK"))                 { peek = true; s = "BODY" + s.substring(9); }
174                     if (s.startsWith("BODY.1"))                      s = "BODY" + s.substring(6);
175                     if (s.indexOf('<') != -1) {
176                         String range = s.substring(s.indexOf('<') + 1, s.indexOf('>'));
177                         s = s.substring(0, s.indexOf('<'));
178                         if (range.indexOf(imapSeparator) == -1) end = Integer.MAX_VALUE;
179                         else {
180                             end = Integer.parseInt(range.substring(range.indexOf(imapSeparator) + 1));
181                             range = range.substring(0, range.indexOf(imapSeparator));
182                         }
183                         start = Integer.parseInt(range);
184                     }
185                     if (s.equals("ENVELOPE") || all || full)          reply.append("ENVELOPE " + envelope(m) + " ");
186                     if (s.equals("FLAGS") || full || all || fast)  reply.append("FLAGS (" + flags(it) + ") ");
187                     if (s.equals("INTERNALDATE") || full || all || fast) reply.append("INTERNALDATE "+quotify(m.arrival)+" ");
188                     if (s.equals("RFC822.SIZE") || full || all || fast) reply.append("RFC822.SIZE " + m.rfc822size() + " ");
189                     if (s.equals("RFC822.HEADER") || s.equals("BODY[HEADER]"))
190                         { reply.append("BODY[HEADER] {" + m.allHeaders.length() + "}\r\n"); reply.append(m.allHeaders); }
191                     if (s.equals("RFC822")||s.equals("RFC822.TEXT")||s.equals("BODY")||s.equals("BODY[]")||s.equals("TEXT")||full)
192                         { reply.append("BODY[TEXT] {" + m.body.length() + "}\r\n"); reply.append(m.body); }
193                     if (s.equals("UID"))                        reply.append("UID " + it.uid());
194                     if (s.equals("MIME"))                       throw new Exn.No("FETCH BODY.MIME not supported");
195                     if (s.startsWith("BODY[HEADER.FIELDS"))     throw new Exn.No("partial headers not supported");
196                     if (s.startsWith("BODY[HEADER.FIELDS.NOT")) throw new Exn.No("partial headers not supported");
197                     if (s.equals("BODYSTRUCTURE"))
198                         reply.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " +
199                                      m.rfc822size()+" "+ m.lines +")");
200                 }
201                 star(it.num() + " FETCH (" + reply.toString() + ")");
202                 // FEATURE: range requests
203                 // FEATURE set seen flag if not BODY.PEEK
204             }
205         }
206
207         // FEATURE: hoist the parsing here
208         public void store(Query q, String what, Token[] flags) {
209             for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
210                 Message m = it.cur();
211                 if (what.charAt(0) == 'F') {
212                     it.deleted(false); it.seen(false); it.flagged(false); it.draft(false); it.answered(false); it.recent(false); }
213                 for(int j=0; j<flags.length; j++) {
214                     String flag = flags[j].flag();
215                     if (flag.equals("Deleted"))  it.deleted(what.charAt(0) != '-');
216                     if (flag.equals("Seen"))     it.seen(what.charAt(0) != '-');
217                     if (flag.equals("Flagged"))  it.flagged(what.charAt(0) != '-');
218                     if (flag.equals("Draft"))    it.draft(what.charAt(0) != '-');
219                     if (flag.equals("Answered")) it.answered(what.charAt(0) != '-');
220                     if (flag.equals("Recent"))   it.recent( what.charAt(0) != '-');
221                 }
222                 selected.add(m);  // re-add (?)
223             }
224         }
225
226         public boolean handleRequest() throws IOException {
227             pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
228             System.err.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
229             pw.flush();
230             while(true) {
231                 String tag = null;
232                 try {
233                     boolean uid = false;
234                     tag = null;
235                     // FIXME better error if atom() fails
236                     tag = atom();
237                     String command = atom();
238                     if (command.equalsIgnoreCase("UID"))             { uid = true; command = atom(); }
239                     if (command.equalsIgnoreCase("AUTHENTICATE"))    { login(astring(), astring()); }
240                     else if (command.equalsIgnoreCase("LIST"))         list(mailbox(), mailboxPattern()); 
241                     else if (command.equalsIgnoreCase("LSUB"))         lsub(mailbox(), mailboxPattern()); 
242                     else if (command.equalsIgnoreCase("CAPABILITY")) { capability(); }
243                     else if (command.equalsIgnoreCase("LOGIN"))        login(astring(), astring());
244                     else if (command.equalsIgnoreCase("LOGOUT"))     { logout(); conn.close(); return false; }
245                     else if (command.equalsIgnoreCase("RENAME"))       rename(mailbox(), atom());
246                     else if (command.equalsIgnoreCase("APPEND"))       append(mailbox(), token());
247                     else if (command.equalsIgnoreCase("EXAMINE"))      select(astring(), true);
248                     else if (command.equalsIgnoreCase("SELECT"))       select(astring(), false);
249                     else if (command.equalsIgnoreCase("COPY"))         copy(Query.num(set()), mailbox());
250                     else if (command.equalsIgnoreCase("DELETE"))       delete(mailbox());
251                     else if (command.equalsIgnoreCase("CHECK"))        check();
252                     else if (command.equalsIgnoreCase("NOOP"))         noop();
253                     else if (command.equalsIgnoreCase("CREATE"))       create(astring());
254                     else if (command.equalsIgnoreCase("STORE"))        store(Query.num(set()), atom(), l());
255                     else if (command.equalsIgnoreCase("FETCH"))        fetch(Query.num(set()), token());
256                     else if (command.equalsIgnoreCase("STATUS"))       status(mailbox(), l());
257                     else                                     throw new Exn.Bad("unrecognized command \"" + command + "\"");
258                     pw.println(tag + " OK " + command + " Completed.");
259                     System.err.println(tag + " OK " + command + " Completed.");
260                 } catch (Exn.Bad b) { pw.println(tag + " Bad " + b.toString()); System.err.println(tag + " Bad " + b.toString()); b.printStackTrace();
261                 } catch (Exn.No n) {  pw.println(tag + " OK " + n.toString()); System.err.println(tag + " OK " + n.toString());
262                 }
263                 pw.flush();
264                 newline();
265             }
266         }
267
268         
269         // Unparsing (printing) logic //////////////////////////////////////////////////////////////////////////////
270
271         static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
272         static String quotify(Date d) { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
273         static String address(Address a) {return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
274         public static String addressList(Object a) {
275             if (a == null) return "NIL";
276             if (a instanceof Address) return "("+address((Address)a)+")";
277             Address[] aa = (Address[])a;
278             StringBuffer ret = new StringBuffer();
279             ret.append("(");
280             for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
281             ret.append(")");
282             return ret.toString();
283         }
284         static String flags(Mailbox.Iterator it) {
285             return 
286                 (it.deleted()  ? "\\Deleted "  : "") +
287                 (it.seen()     ? "\\Seen "     : "") +
288                 (it.flagged()  ? "\\Flagged "  : "") +
289                 (it.draft()    ? "\\Draft "    : "") +
290                 (it.answered() ? "\\Answered " : "") +
291                 (it.recent()   ? "\\Recent "   : "");
292         }
293         static String envelope(Message m) {
294             return
295                 "(" + quotify(m.arrival.toString()) +
296                 " " + quotify(m.subject) +          
297                 " " + addressList(m.from) +      
298                 " " + addressList(m.headers.get("sender")) +
299                 " " + addressList(m.replyto) + 
300                 " " + addressList(m.to) + 
301                 " " + addressList(m.cc) + 
302                 " " + addressList(m.bcc) + 
303                 " " + quotify((String)m.headers.get("in-reply-to")) +
304                 " " + quotify(m.messageid) +
305                 ")";
306         }
307
308
309
310         // Parsing Logic //////////////////////////////////////////////////////////////////////////////
311
312         Query query() {
313             String s = null;
314             boolean not = false;
315             Query q = null;
316             while(true) {
317                 Token t = token();
318                 if (t.type == t.LIST) throw new Exn.No("nested queries not yet supported");
319                 else if (t.type == t.SET) return Query.num(t.set());
320                 s = t.atom();
321                 if (s.equals("NOT")) { not = true; continue; }
322                 if (s.equals("OR"))    return Query.or(query(), query());
323                 if (s.equals("AND"))   return Query.and(query(), query());
324                 break;
325             }
326             if (s.startsWith("UN"))        { not = true; s = s.substring(2); }
327             if (s.equals("ANSWERED"))        q = Query.answered();
328             else if (s.equals("DELETED"))    q = Query.deleted();
329             else if (s.equals("DRAFT"))      q = Query.draft();
330             else if (s.equals("FLAGGED"))    q = Query.flagged();
331             else if (s.equals("RECENT"))     q = Query.recent();
332             else if (s.equals("SEEN"))       q = Query.seen();
333             else if (s.equals("OLD"))      { not = true; q = Query.recent(); }
334             else if (s.equals("NEW"))        q = Query.and(Query.recent(), Query.not(Query.seen()));
335             else if (s.equals("KEYWORD"))    q = Query.header("keyword", flag());
336             else if (s.equals("HEADER"))     q = Query.header(astring(), astring());
337             else if (s.equals("BCC"))        q = Query.header("bcc", astring());
338             else if (s.equals("CC"))         q = Query.header("cc", astring());
339             else if (s.equals("FROM"))       q = Query.header("from", astring());
340             else if (s.equals("TO"))         q = Query.header("to", astring());
341             else if (s.equals("SUBJECT"))    q = Query.header("subject", astring());
342             else if (s.equals("LARGER"))     q = Query.size(n(), Integer.MAX_VALUE);
343             else if (s.equals("SMALLER"))    q = Query.size(Integer.MIN_VALUE, n());
344             else if (s.equals("BODY"))       q = Query.body(astring());
345             else if (s.equals("TEXT"))       q = Query.full(astring());
346             else if (s.equals("BEFORE"))     q = Query.arrival(new Date(0), date());
347             else if (s.equals("SINCE"))      q = Query.arrival(date(), new Date(Long.MAX_VALUE));
348             else if (s.equals("ON"))       { Date d = date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
349             else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), date());
350             else if (s.equals("SENTSINCE"))  q = Query.sent(date(), new Date(Long.MAX_VALUE));
351             else if (s.equals("SENTON"))   { Date d = date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
352             else if (s.equals("UID"))        q = Query.uid(set());
353             return q;
354         }
355
356         class Token {
357             private byte type;
358             private final String s;
359             private final Token[] l;
360             private final int n;
361             private static final byte NIL = 0;
362             private static final byte LIST = 1;
363             private static final byte QUOTED = 2;
364             private static final byte NUMBER = 3;
365             private static final byte ATOM = 4;
366             private static final byte BAREWORD = 5;
367             private static final byte SET = 6;
368             public Token() { n = 0; l = null; s = null; type = NIL; }
369             public Token(String s, boolean quoted) { this.s = s; l = null; type = quoted ? QUOTED : ATOM; n = 0; }
370             public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
371             public Token(int number) { n = number; l = null; s = null; type = NUMBER; }
372
373             public String mailboxPattern() throws Exn.Bad {
374                 if (type == ATOM) return s;
375                 if (type == QUOTED) return s;
376                 throw new Exn.Bad("exepected a mailbox pattern");            
377             }
378             public String flag() throws Exn.Bad {
379                 if (type != ATOM) throw new Exn.Bad("expected a flag");
380                 return s;  // if first char != backslash, it is a keyword-flag
381             }
382             public int n() throws Exn.Bad {
383                 if (type != NUMBER) throw new Exn.Bad("expected number");
384                 return n;
385             }
386             public int nz() throws Exn.Bad {
387                 if (type != NUMBER) throw new Exn.Bad("expected number");
388                 if (n == 0) throw new Exn.Bad("expected nonzero number");
389                 return n;
390             }
391             public String  q() throws Exn.Bad {
392                 if (type == NIL) return null;
393                 if (type != QUOTED) throw new Exn.Bad("expected qstring");
394                 return s;
395             }
396             public Token[] l() throws Exn.Bad {
397                 if (type == NIL) return null;
398                 if (type != LIST) throw new Exn.Bad("expected parenthesized list");
399                 return l;
400             }
401             public int[] set() throws Exn.Bad {
402                 if (type != ATOM) throw new Exn.Bad("expected a messageid set");
403                 Vec ids = new Vec();
404                 StringTokenizer st = new StringTokenizer(s, ",");
405                 while(st.hasMoreTokens()) {
406                     String s = st.nextToken();
407                     if (s.indexOf(':') != -1) {
408                         int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
409                         String end_s = s.substring(s.indexOf(':')+1);
410                         if (end_s.equals("*")) {
411                             ids.addElement(new Integer(start));
412                             ids.addElement(new Integer(-1));
413                         } else {
414                             int end = Integer.parseInt(end_s);
415                             for(int j=start; j<=end; j++) ids.addElement(new Integer(j));
416                         }
417                     } else {
418                         ids.addElement(new Integer(Integer.parseInt(s)));
419                     }
420                 }
421                 int[] ret = new int[ids.size()];
422                 for(int i=0; i<ret.length; i++) ret[i] = ((Integer)ids.elementAt(i)).intValue();
423                 return ret;
424             }
425             public Date date() throws Exn.Bad {
426                 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted date");
427                 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
428                 } catch (ParseException p) { throw new Exn.Bad("invalid date format; " + p); }
429             }
430             public Date datetime() throws Exn.Bad {
431                 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted datetime");
432                 try { return new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").parse(s.trim());
433                 } catch (ParseException p) { throw new Exn.Bad("invalid datetime format " + s + " : " + p); }
434             }
435             public String nstring() throws Exn.Bad {
436                 if (type == NIL) return null;
437                 if (type == QUOTED) return s;
438                 throw new Exn.Bad("expected NIL or string");
439             }
440             public String astring() throws Exn.Bad {
441                 if (type == ATOM) return s;
442                 if (type == QUOTED) return s;
443                 throw new Exn.Bad("expected atom or string");
444             }
445             public String atom() throws Exn.Bad {
446                 if (type != ATOM) throw new Exn.Bad("expected atom");
447                 for(int i=0; i<s.length(); i++) {
448                     char c = s.charAt(i);
449                     if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*')
450                         throw new Exn.Bad("invalid char in atom: " + c);
451                 }
452                 return s;
453             }
454             public Mailbox mailbox() throws Exn.Bad {
455                 if (type == BAREWORD && s.toLowerCase().equals("inbox")) return getMailbox("INBOX", false);
456                 return getMailbox(astring(), false);
457             }
458
459         }
460
461         public char getc() throws IOException {
462             int ret = r.read();
463             if (ret == -1) throw new EOFException();
464             System.err.print((char)ret);
465             System.err.flush();
466             return (char)ret;
467         }
468         public  char peekc() throws IOException {
469             int ret = r.read();
470             if (ret == -1) throw new EOFException();
471             r.unread(ret);
472             return (char)ret;
473         }
474         public  void fill(byte[] b) throws IOException {
475             int num = 0;
476             while (num < b.length) {
477                 int numread = is.read(b, num, b.length - num);
478                 if (numread == -1) throw new EOFException();
479                 num += numread;
480             }
481         }
482
483         public void newline() {
484             try {
485                 for(char c = peekc(); c == ' ';) { getc(); c = peekc(); };
486                 for(char c = peekc(); c == '\r' || c == '\n';) { getc(); c = peekc(); };
487             } catch (IOException e) {
488                 e.printStackTrace();
489             }
490         }
491
492         public Token token() {
493             try {
494                 Vec toks = new Vec();
495                 StringBuffer sb = new StringBuffer();
496                 char c = getc(); while (c == ' ') c = getc();
497                 if (c == '\r' || c == '\n') {
498                     throw new Exn.Bad("unexpected end of line");
499                 } if (c == '{') {
500                     while(peekc() != '}') sb.append(getc());
501                     int octets = Integer.parseInt(sb.toString());
502                     while(peekc() == ' ') getc();   // whitespace
503                     while (getc() != '\n' && getc() != '\r') { }
504                     byte[] bytes = new byte[octets];
505                     fill(bytes);
506                     return new Token(new String(bytes), true);
507                 } else if (c == '\"') {
508                     while(true) {
509                         c = getc();
510                         if (c == '\\') sb.append(getc());
511                         else if (c == '\"') break;
512                         else sb.append(c);
513                     }
514                     return new Token(sb.toString(), true);
515                 } else if (c == ')') {
516                     return null;
517                 } else if (c == '(') {
518                     Token t;
519                     do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
520                     Token[] ret = new Token[toks.size()];
521                     toks.copyInto(ret);
522                     return null;  // FIXME
523                 } else while(true) {
524                     sb.append(c);
525                     c = peekc();
526                     if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '{' || c == '\n' || c == '\r')
527                         return new Token(sb.toString(), false);
528                     getc();
529                 }
530             } catch (IOException e) {
531                 e.printStackTrace();
532                 return null;
533             }
534         }
535
536         // FEATURE: inline these?
537         public String mailboxPattern() throws Exn.Bad { return token().mailboxPattern(); }
538         public String flag() throws Exn.Bad { return token().flag(); }
539         public int n() throws Exn.Bad { return token().n(); }
540         public int nz() throws Exn.Bad { return token().nz(); }
541         public String  q() throws Exn.Bad { return token().q(); }
542         public Token[] l() throws Exn.Bad { return token().l(); }
543         public int[] set() throws Exn.Bad { return token().set(); }
544         public Date date() throws Exn.Bad { return token().date(); }
545         public Date datetime() throws Exn.Bad { return token().datetime(); }
546         public String nstring() throws Exn.Bad { return token().nstring(); }
547         public String astring() throws Exn.Bad { return token().astring(); }
548         public String atom() throws Exn.Bad { return token().atom(); }
549         public Mailbox mailbox() throws Exn.Bad, IOException { return token().mailbox(); }
550     }
551 }