1dab5ef2a915153096c5569833cab8b3ac9762ea
[org.ibex.mail.git] / src / org / ibex / mail / IMAP.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.mail;
6 import org.ibex.io.*;
7 import org.ibex.net.*;
8 import org.ibex.crypto.*;
9 import org.ibex.mail.*;
10 import org.ibex.util.*;
11 import org.ibex.mail.target.*;
12 import java.util.*;
13 import java.net.*;
14 import java.text.*;
15 import java.io.*;
16  
17 // FEATURE: IDLE extension for blackberries
18
19 // FIXME: this is valid    LSUB "" asdfdas%*%*%*%*SFEFGWEF
20 // FIXME: be very careful about where/when we quotify stuff
21 // FIXME: 'UID FOO 100:*' must match at least one message even if all UIDs less than 100
22 // FIXME: LIST should return INBOX if applicable
23
24 // Relevant RFC's:
25 //   RFC 2060: IMAPv4
26 //   RFC 3501: IMAPv4 with clarifications
27 //   RFC 3691: UNSELECT
28 //   RFC 2971: ID
29
30 // to review
31 //   RFC 4466
32 //   RFC 4469
33
34 // FEATURE: make sure we're being case-insensitive enough; probably want to upcase atom()
35 // FEATURE: MIME-queries and BODYSTRUCTURE
36 // FEATURE: READ-WRITE / READ-ONLY status on SELECT
37 // FEATURE: pipelining
38 // FEATURE: support [charset]
39 // FEATURE: \Noselect
40 // FEATURE: subscriptions
41 // FEATURE: tune for efficiency
42 // FEATURE: STARTTLS
43 // FEATURE: asynchronous client notifications (need to re-read RFC)
44
45 public class IMAP {
46
47     public IMAP() { }
48     public static final float version = (float)0.2;
49
50     // API Class //////////////////////////////////////////////////////////////////////////////
51
52     public static interface Client {
53         public void expunge(int uid);
54         public void list(char separator, String mailbox, boolean lsub, boolean phantom);
55         public void fetchResponse(int num, int flags, int size, Message m, int muid);  // m may be null or incomplete
56     }
57
58     public static interface Server {
59         public void      setClient(IMAP.Client client);
60         public String[]  capability();
61         public Hashtable id(Hashtable clientId);
62         public void      copy(Query q, String to);
63         public void      logout();
64         public void      unselect();
65         public void      delete(String m);
66         public void      create(String m);
67         public void      append(String m, int flags, Date arrival, String body);
68         public void      check();
69         public void      noop();
70         public void      close();
71         public void      subscribe(String mailbox);
72         public void      unsubscribe(String mailbox);
73         public int       unseen(String mailbox);
74         public int       recent(String mailbox);
75         public int       count(String mailbox);
76         public int       count();
77         public int       maxuid();
78         public int       uidNext(String mailbox);
79         public int       uidValidity(String mailbox);
80         public int[]     search(Query q, boolean uid);
81         public void      rename(String from, String to);
82         public void      select(String mailbox, boolean examineOnly);
83         public void      setFlags(Query q, int flags, boolean uid, boolean silent);
84         public void      removeFlags(Query q, int flags, boolean uid, boolean silent);
85         public void      addFlags(Query q, int flags, boolean uid, boolean silent);
86         public void      expunge();
87         public void      fetch(Query q, int spec, String[] headers, int start, int end, boolean uid);
88         public void      lsub(String start, String ref);
89         public void      list(String start, String ref);
90         public static class Exn extends MailException { public Exn(String s) { super(s); } }
91         public static class Bad extends Exn { public Bad(String s) { super(s); } }
92         public static class No extends Exn { public No(String s) { super(s); } }
93     }
94
95
96     // MailboxWrapper //////////////////////////////////////////////////////////////////////////////
97
98     /** wraps an IMAP.Server interface around a Mailbox */
99     public static class MailboxWrapper implements Server {
100
101         public static final char sep = '.';
102
103         Mailbox inbox = null;
104         Mailbox selected = null;
105         MailTree root = null;
106         Mailbox selected() { if (selected == null) throw new Bad("no mailbox selected"); return selected; }
107         final Login auth;
108         final Client client;
109
110         public MailboxWrapper(Login auth, Client c) { this.auth=auth; this.client=c;}
111         public void setClient(IMAP.Client client) { }
112
113         private String dirname(String name) { return name.substring(0, name.lastIndexOf(sep)); }
114         private String basename(String name) { return name.substring(name.lastIndexOf(sep)+1); }
115         private Mailbox mailbox(String name, boolean create) { return mailbox(name, create, true); }
116         private Mailbox mailbox(String name, boolean create, boolean throwexn) {
117             if (name.equalsIgnoreCase("inbox")) return inbox;
118             if (name.equalsIgnoreCase("trash")) name = "trash";
119             MailTree mt =  mailboxTree(name, create, throwexn);
120             Mailbox ret = mt==null ? null : mt.getMailbox();
121             if (ret==null && throwexn) throw new Server.No("no such mailbox " + name);
122             return ret;
123         }
124         private MailTree mailboxTree(String name, boolean create) { return mailboxTree(name, create, true); }
125         private MailTree mailboxTree(String name, boolean create, boolean throwexn) {
126             MailTree m = root;
127             for(StringTokenizer st = new StringTokenizer(name, sep + ""); st.hasMoreTokens();)
128                 if ((m = m.slash(st.nextToken(), create)) == null) {
129                     if (throwexn) throw new Server.No("no such mailbox " + name);
130                     return null;
131                 }
132             return m;
133         }
134
135         // FEATURE: not accurate when a wildcard and subsequent non-wildcards both match a single component
136         public void lsub(String start, String ref) { list(start, ref, true); }
137         public void list(String start, String ref) { list(start, ref, false); }
138         public void list(String start, String ref, boolean lsub) {
139
140             // FIXME this might be wrong
141             if (ref.equalsIgnoreCase("inbox")) { client.list(sep,"inbox",lsub,false); return; }
142
143             if (ref.length() == 0) { client.list(sep, start, lsub, false); return; }
144             while (start.endsWith(""+sep)) start = start.substring(0, start.length() - 1);
145             if (ref.endsWith("%")) ref = ref + sep;
146             String[] children = (start.length() == 0 ? root : mailboxTree(start, false)).children();
147             for(int i=0; i<children.length; i++) {
148                 String s = children[i], pre = ref, kid = start + (start.length() > 0 ? sep+"" : "") + s;                
149                 if (mailbox(kid, false) == null) continue;
150                 MailTree phant = mailboxTree(kid, false, false);
151                 if (phant != null) {
152                     boolean phantom = phant.getMailbox()==null;
153                     while(true) {
154                         if (pre.length() == 0) {
155                             if (s.length() == 0)       client.list(sep, kid, lsub, phantom);
156                         } else switch(pre.charAt(0)) {
157                             case sep:        if (s.length() == 0) list(kid, pre.substring(1), lsub);                    break;
158                             case '%':        client.list(sep,kid,lsub,phantom);pre=pre.substring(1); s = "";            continue;
159                             case '*':        client.list(sep,kid,lsub,phantom);list(kid,pre,lsub);pre=pre.substring(1); break;
160                             default:         if (s.length()==0)                                                         break;
161                                 if (s.charAt(0) != pre.charAt(0))                                          break;
162                                 s = s.substring(1); pre = pre.substring(1);                                continue;
163                         }
164                         break;
165                     }
166                 }
167             }
168         }
169
170         public String[] capability() { return new String[] { "IMAP4rev1" , "UNSELECT" /*, "ID"*/ }; }
171         public Hashtable id(Hashtable clientId) {
172             Hashtable response = new Hashtable();
173             response.put("name", IMAP.class.getName());
174             response.put("version", version + "");
175             response.put("os", System.getProperty("os.name", null));
176             response.put("os-version", System.getProperty("os.version", null));
177             response.put("vendor", "none");
178             response.put("support-url", "http://mail.ibex.org/");
179             return response;
180         }   
181
182         public void copy(Query q, String to) { copy(q, mailbox(to, false)); }
183         /*  */ void copy(Query q, Mailbox to) {
184             for(Mailbox.Iterator it=selected().iterator(q);it.next();) to.insert(it.cur(), it.getFlags() | Mailbox.Flag.RECENT); }
185
186         public void unselect() { selected = null; }
187
188         public void delete(String m0) { mailboxTree(dirname(m0),false).rmdir(basename(m0)); }
189
190         public void rename(String from0, String to) {
191             Mailbox from = mailbox(from0, false);
192             if (from.equals(inbox))                { from.copy(Query.all(), mailbox(to, true)); }
193             else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), mailbox(to, true)); delete(from0); }
194             else mailboxTree(dirname(from0), false)
195                      .rename(dirname(from0),
196                              mailboxTree(dirname(to),
197                                          true /* required by IMAP */),
198                              basename(to));
199         }
200
201         public void create(String m) { mailbox(m, true, false); }
202         public void append(String m,int f,Date a,String b) { try {
203             // FIXME: more efficient streaming here?
204             mailbox(m,false).insert(Message.newMessage(new Fountain.StringFountain(b)), f | Mailbox.Flag.RECENT);
205         } catch (Message.Malformed e) { throw new No(e.getMessage()); } }
206         public void check() { }
207         public void noop() { }
208         public void logout() { }
209         public void close() {
210             for(Mailbox.Iterator it=selected().iterator(Query.deleted()); it.next();) {
211                 Log.error("imap", "deleting a message due to close(): " + it.cur().summary());
212                 it.delete();
213             }
214         }
215         public void expunge() { for(Mailbox.Iterator it = selected().iterator(Query.deleted());it.next();) expunge(it); }
216         public void expunge(Mailbox.Iterator it) {
217             client.expunge(it.uid());
218             Log.error("imap", "deleting a message due to expunge(): " + it.cur().summary());
219             it.delete();
220         }
221         public void subscribe(String mailbox) { }
222         public void unsubscribe(String mailbox) { }
223         public int maxuid() {
224             int ret = 0;
225             Mailbox mb = selected();
226             if (mb == null) return 0;
227             return mb.maxuid();
228         }
229         public int unseen(String mailbox)      { return mailbox(mailbox, false).count(Query.not(Query.seen())); }
230         public int recent(String mailbox)      { return mailbox(mailbox, false).count(Query.recent()); }
231         public int count(String mailbox)       { return mailbox(mailbox, false).count(Query.all()); }
232         public int count()                     { return selected().count(Query.all()); }
233         public int uidNext(String mailbox)     { return mailbox(mailbox, false).uidNext(); }
234         public int uidValidity(String mailbox) { return Math.abs(mailbox(mailbox, false).uidValidity()); }
235         public void select(String mailbox, boolean examineOnly) { selected = mailbox(mailbox, false); }
236
237         public int[] search(Query q, boolean uid) {
238             Vec.Int vec = new Vec.Int();
239             for(Mailbox.Iterator it = selected().iterator(q); it.next();) {
240                 vec.addElement(uid ? it.uid() : it.imapNumber());
241                 if ((it.getFlags() & Mailbox.Flag.RECENT) != 0)
242                     it.setFlags(it.getFlags() & ~Mailbox.Flag.RECENT);
243             }
244             return vec.dump();
245         }
246
247         public void setFlags(Query q, int f, boolean uid, boolean silent)    { doFlags(q, f, uid, 0, silent); }
248         public void addFlags(Query q, int f, boolean uid, boolean silent)    { doFlags(q, f, uid, 1, silent); }
249         public void removeFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, -1, silent); }
250         private void doFlags(Query q, int flags, boolean uid, int style, boolean silent) {
251             for(Mailbox.Iterator it = selected().iterator(q);it.next();) {
252                 // FIXME: what's going on here with the recent flag?
253                 //boolean recent = it.getFlag(Mailbox.Flag.RECENT);
254                 //try { throw new Exception("flags " + flags); } catch (Exception e) { Log.error(this, e); }
255                 if (style == -1)     it.setFlags(it.getFlags() & ~flags);
256                 else if (style == 0) it.setFlags(flags);
257                 else if (style == 1) it.setFlags(it.getFlags() | flags);
258                 //it.setFlag(Mailbox.Flag.RECENT, recent);
259                 if (!silent) client.fetchResponse(it.imapNumber(), it.getFlags(), -1, null, it.uid());
260             }
261         }
262
263         public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid) {
264             for(Mailbox.Iterator it = selected().iterator(q); it.next(); ) {
265                 // FIXME it would be great if we could avoid instantiating the entire message just because RFC822SIZE was requested
266                 Message message =
267                     ((spec & (BODYSTRUCTURE | RFC822 | RFC822TEXT | RFC822SIZE)) != 0)
268                     ? it.cur()
269                     : ((spec & (ENVELOPE | INTERNALDATE | FIELDS | FIELDSNOT | RFC822SIZE | HEADERNOT | HEADER)) != 0)
270                     ? Message.newMessage(Fountain.Util.concat(it.head(), Fountain.Util.create("\r\n\r\n")))
271                     : null;
272                 if (message != null) Log.warn("spec", spec);
273                 long size = message == null ? 0 : message.getLength();
274                 client.fetchResponse(it.imapNumber(), it.getFlags(), (int)size, message,it.uid());
275                 it.setFlags(it.getFlags() & ~Mailbox.Flag.RECENT);
276             }
277         }
278     }
279
280     // Single Session Handler //////////////////////////////////////////////////////////////////////////////
281
282     /** takes an IMAP.Server and exposes it to the world as an IMAP server on a TCP socket */
283     public static class Listener implements Client {
284         String selectedName = null;
285         Mailbox inbox = null;
286         MailTree root = null;
287         Server api;
288         Parser parser = null;
289         Connection conn = null;
290         Login auth;
291         public Listener(Login auth) { api = new IMAP.MailboxWrapper(this.auth = auth, this); }
292         Parser.Token token() { return parser.token(); }
293         Parser.Token token(boolean freak) { return parser.token(freak); }
294         void println(String s) {
295             conn.println(s);
296             //Log.info("", s);
297         }
298         void newline() { parser.newline(); }
299         Query query(int max) { return parser.query(max, maxn(true)); }
300
301         public void login(String u, String p) {
302             Object ret;
303             if ((ret = auth.login(u,p,IMAP.class)) == null) throw new Server.No("Login failed.");
304             if (ret instanceof IMAP.Server) {
305                 api = (IMAP.Server)ret;
306                 api.setClient(this);
307             } else {
308                 Account account = (Account)ret;
309                 ((MailboxWrapper)api).root = root = account.getMailbox(IMAP.class);
310                 MailTree ibt = root.slash("inbox", false);
311                 Mailbox ib = ibt==null ? null : ibt.getMailbox();
312                 ((MailboxWrapper)api).inbox = inbox = ib;
313             }
314         }
315
316         private int maxn(boolean uid) { return uid ? api.maxuid() : api.count(); }
317
318         public void handleRequest(Connection conn) {
319             this.conn = conn;
320             parser = new Parser(conn);
321             conn.setTimeout(30 * 60 * 1000);
322             println("* OK " + conn.vhost + " " + IMAP.class.getName() + " IMAP4rev1 [RFC3501] v" + version + " server ready");
323             for(String tag = null;;) try {
324                 conn.flush();
325                 boolean uid = false;
326                 tag = null; Parser.Token tok = token(); if (tok == null) return; tag = tok.astring();
327                 String command = token().atom();
328                 if (command.equalsIgnoreCase("UID")) { uid = true; command = token().atom(); }
329                 int commandKey = ((Integer)commands.get(command.toUpperCase())).intValue();
330                 switch(commandKey) {
331                     case LOGIN:        login(token().astring(), token().astring()); break;
332                     case CAPABILITY:   println("* CAPABILITY " + Printer.join(" ", api.capability())); break;
333                     case AUTHENTICATE: throw new Server.No("AUTHENTICATE not supported");
334                     case LOGOUT:       api.logout(); println("* BYE"); conn.close(); return;
335                     case LIST:         api.list(token().q(), token().astring()); break; /*astring is a hack for EUDORA*/
336                     case LSUB:         api.lsub(token().q(), token().q()); break;
337                     case SUBSCRIBE:    api.subscribe(token().astring()); break;
338                     case UNSUBSCRIBE:  api.unsubscribe(token().astring()); break;
339                     case RENAME:       api.rename(token().astring(), token().astring()); break;
340                     case DELETE:       api.delete(token().atom()); break;
341                     case CHECK:        selected(); api.check(); break;
342                     case NOOP:         api.noop(); break;
343                     case CLOSE:        selected(); api.close(); break;
344                     case EXPUNGE:      selected(); api.expunge(); break;
345                     case UNSELECT:     selected(); api.unselect(); selected = false; break;
346                     case CREATE:       api.create(token().astring()); break;
347                     case FETCH:        selected(); lastuid = uid; _fetch((uid
348                                                                           ? Query.uid(token().set(maxn(uid)))
349                                                                           : Query.imapNumber(token().set(maxn(uid)))),
350                                                                          lastfetch=token().lx(), 0, 0, 0, uid, 0); break;
351                     case COPY:         selected(); api.copy(uid
352                                                             ? Query.uid(token().set(maxn(uid)))
353                                                             : Query.imapNumber(token().set(maxn(uid))), token().astring()); break;
354                     case SEARCH: {
355                         selected();
356                         int[] result = api.search(query(maxn(uid)), uid);
357                         /*if (result.length > 0)*/ println("* SEARCH " + Printer.join(result));
358                         break;
359                     }
360                     case EXAMINE:
361                     case SELECT: {
362                         String mailbox = token().astring();
363                         api.select(mailbox, commandKey==EXAMINE);
364                         println("* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
365                         println("* " + api.count(mailbox)  + " EXISTS");
366                         println("* " + api.recent(mailbox) + " RECENT");
367                         println("* OK [UNSEEN " + api.unseen(mailbox) + "]");
368                         println("* OK [UIDVALIDITY " + api.uidValidity(mailbox) + "] UIDs valid");
369                         println("* OK [UIDNEXT " + api.uidNext(mailbox) + "]");
370                         println("* OK [PERMANENTFLAGS (\\Seen)]");
371                         selected = true;
372                         break; }
373                     case STATUS: {
374                         String mailbox = token().astring();  // hack for GNUS buggy client
375                         Parser.Token[] list = token().l();
376                         String response = "";
377                         for(int i=0; i<list.length; i++) {
378                             String s = list[i].atom().toUpperCase();
379                             if (i>0) response += " ";
380                             if (s.equals("MESSAGES"))    response += "MESSAGES "    + api.count(mailbox);
381                             if (s.equals("RECENT"))      response += "RECENT "      + api.recent(mailbox);
382                             if (s.equals("UIDNEXT"))     response += "UIDNEXT "     + api.uidNext(mailbox);
383                             if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + api.uidValidity(mailbox);
384                             if (s.equals("UNSEEN"))      response += "UNSEEN "      + api.unseen(mailbox);
385                         }
386                         println("* STATUS " + mailbox + " (" + response + ")");
387                         break;
388                     }
389                     case APPEND: { 
390                         String m = token().astring();
391                         int flags = 0;
392                         Date arrival = new Date();
393                         Parser.Token t = token();
394                         if (t.type == t.LIST)   { flags = t.flags();      t = token(); }
395                         Parser.Token t2 = token(false);
396                         if (t2 != null) { arrival = t.datetime(); t = t2; }
397                         api.append(m, flags, arrival, t.q());
398                         break; }
399                     case STORE: {
400                         selected();
401                         Query q = uid ? Query.uid(token().set(maxn(uid))) : Query.imapNumber(token().set(maxn(uid)));
402                         String s = token().atom().toUpperCase();
403                         int flags = token().flags();
404                         if (s.equals("FLAGS"))              api.setFlags(q,    flags, uid, false);
405                         else if (s.equals("+FLAGS"))        api.addFlags(q,    flags, uid, false);
406                         else if (s.equals("-FLAGS"))        api.removeFlags(q, flags, uid, false);
407                         else if (s.equals("FLAGS.SILENT"))  api.setFlags(q,    flags, uid, true);
408                         else if (s.equals("+FLAGS.SILENT")) api.addFlags(q,    flags, uid, true);
409                         else if (s.equals("-FLAGS.SILENT")) api.removeFlags(q, flags, uid, true);
410                         else throw new Server.Bad("unknown STORE specifier " + s);
411                         break; }
412                     default: throw new Server.Bad("unrecognized command \"" + command + "\"");
413                 }
414                 println(tag+" OK "+command+" Completed. " +
415                         (commandKey == LOGIN ? ("[CAPABILITY "+Printer.join(" ", api.capability())+"]") : ""));
416                 try {
417                     newline();
418                 } catch (Stream.EOF e) {
419                     Log.info(this, "connection closed");
420                     return;
421                 }
422             } catch (Server.Bad b) { println(tag==null ? "* BAD Invalid tag":(tag + " Bad " + b.toString())); Log.warn(this,b);
423             } catch (Server.No n)  { println(tag==null?"* BAD Invalid tag":(tag+" No "  + n.toString())); Log.warn(this,n);
424             }
425         }
426
427         private Parser.Token[] lastfetch = null; // hack
428         private boolean lastuid = false;  // hack
429         private boolean selected = false;
430         private void selected() { if (!selected) throw new Server.Bad("no mailbox selected"); }
431
432         // Callbacks //////////////////////////////////////////////////////////////////////////////
433
434         public void expunge(int uid) { println("* " + uid + " EXPUNGE"); }
435         public void fetchResponse(int n, int f, int size, Message m, int muid) { _fetch(m, lastfetch, n, f, size, lastuid, muid); }
436         public void list(char sep, String mb, boolean sub, boolean p) {
437             println("* " + (sub?"LSUB":"LIST")+" ("+(p?"\\Noselect":"")+") \""+sep+"\" \""+mb+"\"");}
438
439         /**
440          *   Parse a fetch request <i>or</i> emit a fetch reply.
441          *
442          *   To avoid duplicating tedious parsing logic, this function
443          *   performs both of the following tasks:
444          *      - parse the fetch request in Token[] t and return a fetch spec
445          *      - emit a fetch reply for the parsed spec with respect to message m
446          */
447         private void _fetch(Object o, Parser.Token[] t, int num, int flags, int size, boolean uid, int muid) {
448             Query q   = o == null ? null : o instanceof Query ? (Query)o : null;
449             Message m = o == null ? null : o instanceof Message ? (Message)o : null;
450             boolean e = q == null;
451
452             // asynchronous flags update
453             if (size == -1) {
454                 println("* " + num + " FETCH (FLAGS " + Printer.flags(flags) + (uid?(" UID "+muid):"") + ")");
455                 return;
456             }
457
458             lastfetch = t;
459             int spec = 0;                              // spec; see constants for flags
460             int start = 0, len = 0;
461             String[] headers = null;
462             StringBuffer r = new StringBuffer();
463             if (e) { r.append(num); r.append(" FETCH ("); }
464             int initlen = r.length();
465             if (uid) {
466                 boolean good = false;
467                 for(int i=0; i<t.length; i++)
468                     if ((t[i].type == Parser.Token.QUOTED || t[i].type == Parser.Token.ATOM) &&
469                         t[i].astring().equalsIgnoreCase("UID")) good = true;
470                 if (!good) {
471                     Parser.Token[] t2 = new Parser.Token[t.length + 1];
472                     System.arraycopy(t, 0, t2, 0, t.length);
473                     t2[t2.length - 1] = parser.token("UID");
474                     lastfetch = (t = t2);
475                 }
476             }
477             if (t.length == 0 && (t[0].type == Parser.Token.QUOTED || t[0].type == Parser.Token.ATOM)) {
478                 if (t[0].astring().equalsIgnoreCase("ALL"))
479                     t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"),
480                                       parser.token("ENVELOPE"), parser.token("RFC822.SIZE") };
481                 else if (t[0].astring().equalsIgnoreCase("FULL"))
482                     t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"), parser.token("BODY"), 
483                                       parser.token("ENVELOPE"), parser.token("RFC822.SIZE") };
484                 else if (t[0].astring().equalsIgnoreCase("FAST"))
485                     t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"),
486                                       parser.token("RFC822.SIZE") };
487             }
488             boolean looked_at_body = false;
489             for(int i=0; i<t.length; i++) {
490                 if (r.length() > initlen) r.append(" ");
491                 if (t[i] == null || t[i].s == null) continue;
492                 String s = t[i].s.toUpperCase();
493                 r.append(s.equalsIgnoreCase("BODY.PEEK")?"BODY":s);
494                 if (s.equals("BODYSTRUCTURE")) {       spec|=BODYSTRUCTURE;if(e){r.append(" ");r.append(Printer.bodystructure(m));}
495                 } else if (s.equals("ENVELOPE")) {     spec|=ENVELOPE;     if(e){r.append(" ");r.append(Printer.envelope(m));}
496                 } else if (s.equals("FLAGS")) {        spec|=FLAGS;        if(e){r.append(" ");r.append(Printer.flags(flags));}
497                 } else if (s.equals("INTERNALDATE")) { spec|=INTERNALDATE; if(e){r.append(" ");r.append(Printer.date(m.arrival));}
498                 } else if (s.equals("RFC822")) {       spec|=RFC822;       if(e){r.append(" ");r.append(Printer.message(m));}
499                 } else if (s.equals("RFC822.TEXT")) {  spec|=RFC822TEXT;   if(e){r.append(" ");r.append(Printer.qq(m.getStream()));}
500                 } else if (s.equals("RFC822.HEADER")){ spec|=HEADER;       if(e){r.append(" ");r.append(Printer.qq(m.headers.getStream().append("\r\n")));}
501                 } else if (s.equals("RFC822.SIZE")) {  spec|=RFC822SIZE;   if(e){r.append(" ");r.append(m.getLength());}
502                 } else if (s.equals("UID")) {          spec|=UID;          if(e){r.append(" ");r.append(muid); }
503                 } else if (!(s.equals("BODY.PEEK") || s.equals("BODY"))) { throw new Server.No("unknown fetch argument: " + s);
504                 } else {
505                     if (s.equalsIgnoreCase("BODY.PEEK"))   spec |= PEEK;
506                     looked_at_body = true;
507                     if (i >= t.length - 1 || t[i+1].type != Parser.Token.LIST) {
508                         // not sure why this was uncommented....
509                         //spec |= BODYSTRUCTURE;
510                         if (e) { r.append(" "); r.append(Printer.bodystructure(m)); } continue;
511                         //if (e) { r.append(" "); r.append(Printer.qq(m.getBody().getStream())); } continue;
512                     }
513                     Fountain payload = Fountain.Util.create("");
514                     r.append("[");
515                     Parser.Token[] list = t[++i].l();
516                     s = list.length == 0 ? "" : list[0].s.toUpperCase();
517                     r.append(s);
518                     if (list.length == 0)                   { spec |= RFC822TEXT;   if(e) payload = m; }
519                     else if (s.equals("") || s.equals("1")) { spec |= RFC822TEXT;   if(e) payload = m; }
520                     else if (s.equals("TEXT"))              { spec |= RFC822TEXT;   if(e) payload = m.getBody(); }
521                     else if (s.equals("HEADER"))            { spec |= HEADER;       if(e) payload = Fountain.Util.concat(m.headers, Fountain.Util.create("\r\n")); }
522                     else if (s.equals("HEADER.FIELDS"))     { spec |= FIELDS;       payload=Fountain.Util.create(headers(r,t[i].l()[1].sl(),false,m,e)); }
523                     else if (s.equals("HEADER.FIELDS.NOT")) { spec |= FIELDSNOT;    payload=Fountain.Util.create(headers(r,t[i].l()[1].sl(),true,m,e)); }
524                     else if (s.equals("MIME")) {              throw new Server.Bad("MIME not supported"); }
525                     else                                      throw new Server.Bad("unknown section type " + s);
526
527                     if (i<t.length - 1 && (t[i+1].s != null && t[i+1].s.startsWith("<"))) {
528                         i++;
529                         s = t[i].s.substring(1, t[i].s.indexOf('>'));
530                         int dot = s.indexOf('.');
531                         start = dot == -1 ? Integer.parseInt(s) : Integer.parseInt(s.substring(0, s.indexOf('.')));
532                         len   = dot == -1 ? -1 : Integer.parseInt(s.substring(s.indexOf('.') + 1));
533                         if (e) {
534                             if (start == 0 && len == -1) {
535                             } else if (len == -1) {
536                                 payload = Fountain.Util.subFountain(payload, start);
537                             } else {
538                                 len = (int)Math.min(len, payload.getLength()-start);
539                                 payload = Fountain.Util.subFountain(payload, start, len);
540                             }
541                             r.append("]");
542                             r.append("<"+start+"> ");
543                         }
544                     } else {
545                         if (e) r.append("] ");
546                     }
547                     if (e) r.append(Printer.qq(payload.getStream()));
548                 }
549             }
550             if ((spec & PEEK) == 0 && looked_at_body && e)
551                 api.addFlags(Query.imapNumber(new int[] { num, num }), Mailbox.Flag.SEEN, false, false);
552             if (e) {
553                 r.append(")");
554                 println("* " + r.toString());
555             } else {
556                 api.fetch(q, spec, headers, start, (len==-1?0:len), uid);
557             }
558         }
559
560         private String headers(StringBuffer r, String[] headers, boolean negate, Message m, boolean e) {
561             String payload = "";
562             if (e) r.append(" (");
563             if (!negate) {
564                 if(e) for(int j=0; j<headers.length; j++) {
565                     r.append(headers[j] + (j<headers.length-1?" ":""));
566                     if (m.headers.get(headers[j]) != null) payload += headers[j]+": "+m.headers.get(headers[j])+"\r\n";
567                 }
568             } else {
569                 throw new Server.No("HEADERS.NOT temporarily disaled");
570                 /*
571                 if (e) for(int j=0; j<headers.length; j++) r.append(headers[j] + (j<headers.length-1?" ":""));
572                 if(e) { OUTER: for(Enumeration x=m.headers.keys(); x.hasMoreElements();) {
573                     String key = (String)x.nextElement();
574                     for(int j=0; j<headers.length; j++) if (key.equalsIgnoreCase(headers[j])) continue OUTER;
575                     payload += key + ": " + m.headers.get(key)+"\r\n";
576                 } }
577                 */
578             }
579             if (e) r.append(")");
580             return payload + "\r\n";
581         }
582
583         private static final Hashtable commands = new Hashtable();
584         private static final int UID = 0;          static { commands.put("UID", new Integer(UID)); }
585         private static final int AUTHENTICATE = 1; static { commands.put("AUTHENTICATE", new Integer(AUTHENTICATE)); }
586         private static final int LIST = 2;         static { commands.put("LIST", new Integer(LIST)); }
587         private static final int LSUB = 3;         static { commands.put("LSUB", new Integer(LSUB)); }
588         private static final int SUBSCRIBE = 4;    static { commands.put("SUBSCRIBE", new Integer(SUBSCRIBE)); }
589         private static final int UNSUBSCRIBE = 5;  static { commands.put("UNSUBSCRIBE", new Integer(UNSUBSCRIBE)); }
590         private static final int CAPABILITY = 6;   static { commands.put("CAPABILITY", new Integer(CAPABILITY)); }
591         private static final int ID = 7;           static { commands.put("ID", new Integer(ID)); }
592         private static final int LOGIN = 8;        static { commands.put("LOGIN", new Integer(LOGIN)); }
593         private static final int LOGOUT = 9;       static { commands.put("LOGOUT", new Integer(LOGOUT)); }
594         private static final int RENAME = 10;      static { commands.put("RENAME", new Integer(RENAME)); }
595         private static final int EXAMINE = 11;     static { commands.put("EXAMINE", new Integer(EXAMINE)); }
596         private static final int SELECT = 12;      static { commands.put("SELECT", new Integer(SELECT)); }
597         private static final int COPY = 13;        static { commands.put("COPY", new Integer(COPY)); }
598         private static final int DELETE = 14;      static { commands.put("DELETE", new Integer(DELETE)); }
599         private static final int CHECK = 15;       static { commands.put("CHECK", new Integer(CHECK)); }
600         private static final int NOOP = 16;        static { commands.put("NOOP", new Integer(NOOP)); }
601         private static final int CLOSE = 17;       static { commands.put("CLOSE", new Integer(CLOSE)); }
602         private static final int EXPUNGE = 18;     static { commands.put("EXPUNGE", new Integer(EXPUNGE)); }
603         private static final int UNSELECT = 19;    static { commands.put("UNSELECT", new Integer(UNSELECT)); }
604         private static final int CREATE = 20;      static { commands.put("CREATE", new Integer(CREATE)); }
605         private static final int STATUS = 21;      static { commands.put("STATUS", new Integer(STATUS)); }
606         private static final int FETCH = 22;       static { commands.put("FETCH", new Integer(FETCH)); }
607         private static final int APPEND = 23;      static { commands.put("APPEND", new Integer(APPEND)); }
608         private static final int STORE = 24;       static { commands.put("STORE", new Integer(STORE)); }
609         private static final int SEARCH = 25;      static { commands.put("SEARCH", new Integer(SEARCH)); }
610     }
611
612     public static class Parser {
613         private Stream stream;
614         public Parser(Stream from) { this.stream = from; }
615         public Token token(String s) { return new Token(s); }
616         protected Query query(int max, int maxuid) {
617             String s = null;
618             boolean not = false;
619             Query q = null;
620             Query ret = null;
621             while(true) {
622                 Parser.Token t = token(false);
623                 if (t == null) break;
624                 if (t.type == t.LIST) throw new Server.No("nested queries not yet supported FIXME");
625                 else if (t.type == t.SET) return Query.imapNumber(t.set(max));
626                 s = t.atom().toUpperCase();
627                 if (s.equals("NOT"))   return Query.not(query(max, maxuid));
628                 if (s.equals("OR"))    return Query.or(query(max, maxuid), query(max, maxuid));    // FIXME parse rest of list
629                 if (s.equals("AND"))   return Query.and(query(max, maxuid), query(max, maxuid));
630
631                 if (s.startsWith("UN"))        { not = true; s = s.substring(2); }
632                 if (s.equals("ANSWERED"))        q = Query.answered();
633                 else if (s.equals("DELETED"))    q = Query.deleted();
634                 else if (s.equals("ALL"))        q = Query.all();
635                 else if (s.equals("DRAFT"))      q = Query.draft();
636                 else if (s.equals("FLAGGED"))    q = Query.flagged();
637                 else if (s.equals("RECENT"))     q = Query.recent();
638                 else if (s.equals("SEEN"))       q = Query.seen();
639                 else if (s.equals("OLD"))      { not = true; q = Query.recent(); }
640                 else if (s.equals("NEW"))        q = Query.and(Query.recent(), Query.not(Query.seen()));
641                 else if (s.equals("KEYWORD"))    q = Query.header("keyword", token().flag());
642                 else if (s.equals("HEADER"))     q = Query.header(token().astring(), token().astring());
643                 else if (s.equals("BCC"))        q = Query.header("bcc", token().astring());
644                 else if (s.equals("CC"))         q = Query.header("cc", token().astring());
645                 else if (s.equals("FROM"))       q = Query.header("from", token().astring());
646                 else if (s.equals("TO"))         q = Query.header("to", token().astring());
647                 else if (s.equals("SUBJECT"))    q = Query.header("subject", token().astring());
648                 else if (s.equals("LARGER"))     q = Query.size(token().n(), Integer.MAX_VALUE);
649                 else if (s.equals("SMALLER"))    q = Query.size(Integer.MIN_VALUE, token().n());
650                 else if (s.equals("BODY"))       q = Query.body(token().astring());
651                 else if (s.equals("TEXT"))       q = Query.full(token().astring());
652                 else if (s.equals("BEFORE"))     q = Query.arrival(new Date(0), token().date());
653                 else if (s.equals("SINCE"))      q = Query.arrival(token().date(), new Date(Long.MAX_VALUE));
654                 else if (s.equals("ON"))       { Date d = token().date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
655                 else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), token().date());
656                 else if (s.equals("SENTSINCE"))  q = Query.sent(token().date(), new Date(Long.MAX_VALUE));
657                 else if (s.equals("SENTON"))   { Date d = token().date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
658                 else if (s.equals("UID"))        q = Query.uid(token().set(max));
659                 q = not ? Query.not(q) : q;
660                 ret = ret == null ? q : Query.and(ret, q);
661             }
662             return ret;
663         }
664
665         private static void bad(String s) { throw new Server.Bad(s); }
666         class Token {
667             public final byte type;
668             private final String s;
669             private final Parser.Token[] l;
670             private final int n;
671             private static final byte NIL = 0, LIST = 1, QUOTED = 2, NUMBER = 3, ATOM = 4, BAREWORD = 5, SET = 6;
672             public Token()                         { this.s = null; n = 0;      l = null; type = NIL; }
673             public Token(String s)                 { this(s, false); }
674             public Token(String s, boolean quoted) { this.s = s;    n = 0;      l = null; type = quoted ? QUOTED : ATOM;  }
675             public Token(Parser.Token[] list)      { this.s = null; n = 0;      l = list; type = LIST; }
676             public Token(int number)               { this.s = null; n = number; l = null; type = NUMBER; }
677
678             public String   flag()    { if (type != ATOM) bad("expected a flag"); return s; }
679             public int      n()       { if (type != NUMBER) bad("expected number"); return n; }
680             public int      nz()      { int n = n(); if (n == 0) bad("expected nonzero number"); return n; }
681             public String   q()       { if (type == NIL) return null; if (type != QUOTED) bad("expected qstring"); return s; }
682             public Parser.Token[]  l()       { if (type == NIL) return null; if (type != LIST) bad("expected list"); return l; }
683             public Parser.Token[]  lx()      {
684                 if (type == LIST) return l;
685                 Vec v = new Vec();
686                 v.addElement(this);
687                 while(true) {
688                     Parser.Token t = token(false);
689                     if (t == null) break;
690                     v.addElement(t);
691                 }
692                 Parser.Token[] ret = new Parser.Token[v.size()];
693                 v.copyInto(ret);
694                 return ret;
695             }
696             public String   nstring() { if (type==NIL) return null; if (type!=QUOTED) bad("expected nstring"); return s; }
697             public String   astring() {
698                 if (type != ATOM && type != QUOTED) bad("expected atom or string");
699                 if (s == null) bad("astring cannot be null");
700                 return s; }
701             public String[] sl() {
702                 if (type == NIL) return null;
703                 if (type != LIST) bad("expected list");
704                 String[] ret = new String[l.length];
705                 for(int i=0; i<ret.length; i++) ret[i] = l[i].s;
706                 return ret;
707             }
708             public int flags() {
709                 if (type != LIST) bad("expected flag list");
710                 int ret = 0;
711                 for(int i=0; i<l.length; i++) {
712                     String flag = l[i].s;
713                     if (flag.equals("\\Deleted"))       ret |= Mailbox.Flag.DELETED;
714                     else if (flag.equals("\\Seen"))     ret |= Mailbox.Flag.SEEN;
715                     else if (flag.equals("\\Flagged"))  ret |= Mailbox.Flag.FLAGGED;
716                     else if (flag.equals("\\Draft"))    ret |= Mailbox.Flag.DRAFT;
717                     else if (flag.equals("\\Answered")) ret |= Mailbox.Flag.ANSWERED;
718                     else if (flag.equals("\\Recent"))   ret |= Mailbox.Flag.RECENT;
719                 }
720                 return ret;
721             }
722             public int[] set(int largest) {
723                 if (type != ATOM) bad("expected a messageid set");
724                 Vec.Int ids = new Vec.Int();
725                 StringTokenizer st = new StringTokenizer(s, ",");
726                 while(st.hasMoreTokens()) {
727                     String s = st.nextToken();
728                     if (s.indexOf(':') == -1) {
729                         if (s.equals("*")) {
730                             ids.addElement(largest);
731                             ids.addElement(largest);
732                         } else {
733                             ids.addElement(Integer.parseInt(s));
734                             ids.addElement(Integer.parseInt(s));
735                         }
736                         continue; }
737                     int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
738                     String end_s = s.substring(s.indexOf(':')+1);
739                     int end = end_s.equals("*") ? largest : Integer.parseInt(end_s);
740                     for(int j=Math.min(start,end); j<=Math.max(start,end); j++) {
741                         ids.addElement(j);
742                         ids.addElement(j);
743                     }
744                 }
745                 return ids.dump();
746             }
747             public Date date() {
748                 if (type != QUOTED && type != ATOM) bad("Expected quoted or unquoted date");
749                 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
750                 } catch (ParseException p) { throw new Server.Bad("invalid date format; " + p); }
751             }
752             public Date datetime() {
753                 if (type != QUOTED) bad("Expected quoted datetime");
754                 try { return new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss zzzz").parse(s.trim());
755                 } catch (ParseException p) { throw new Server.Bad("invalid datetime format " + s + " : " + p); }
756             }
757             public String atom() {
758                 if (type != ATOM) bad("expected atom");
759                 for(int i=0; i<s.length(); i++) {
760                     char c = s.charAt(i);
761                     if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*' || c == '\"' | c == '\\')
762                         bad("invalid char in atom: " + c);
763                 }
764                 return s;
765             }
766         }
767
768         public void newline() { stream.readln(); }
769
770         public Token token() { return token(true); }
771         public Token token(boolean freak) {
772             Vec toks = new Vec();
773             StringBuffer sb = new StringBuffer();
774             char c = stream.getc(); while (c == ' ') c = stream.getc();
775             if (c == '\r' || c == '\n') { if (freak) bad("unexpected end of line"); return null; }
776             else if (c == '{') {
777                 while(stream.peekc() != '}') sb.append(stream.getc());
778                 stream.getc();
779                 stream.println("+ Ready when you are...");
780                 int octets = Integer.parseInt(sb.toString());
781                 while(stream.peekc() == ' ') stream.getc();   // whitespace
782                 while(stream.peekc() == '\n' || stream.peekc() == '\r') stream.getc();
783                 byte[] bytes = new byte[octets];
784                 int numread = 0;
785                 while(numread < bytes.length) {
786                     int n = stream.read(bytes, numread, bytes.length - numread);
787                     if (n == -1) bad("end of stream while reading IMAP qstring");
788                     numread += n;
789                 }
790                 return new Token(new String(bytes), true);
791             } else if (c == '\"') {
792                 while(true) {
793                     c = stream.getc();
794                     if (c == '\\') sb.append(stream.getc());
795                     else if (c == '\"') break;
796                     else sb.append(c);
797                 }
798                 return new Token(sb.toString(), true);
799                 
800                 // NOTE: this is technically a violation of the IMAP grammar, since atoms like FOO[BAR should be legal
801             } else if (c == ']' || c == ')') { return null;
802             } else if (c == '[' || c == '(') {
803                 Token t;
804                 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
805                 Token[] ret = new Token[toks.size()];
806                 toks.copyInto(ret);
807                 return new Token(ret);
808                 
809             } else while(true) {
810                 sb.append(c);
811                 c = stream.peekc();
812                 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '[' || c == ']' ||
813                     c == '{' || c == '\n' || c == '\r')
814                     return new Token(sb.toString(), false);
815                 stream.getc();
816             }
817         }
818     }
819     
820     public static class Printer {
821             static String quotify(String s){
822                 return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
823             static String quotify(Date d) {
824                 return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
825             static String address(Address a) {
826                 return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
827             public static String addressList(Object a) {
828                 if (a == null) return "NIL";
829                 if (a instanceof Address) return "("+address((Address)a)+")";
830                 if (a instanceof String) return "("+address(Address.parse((String)a))+")";
831                 Address[] aa = (Address[])a;
832                 StringBuffer ret = new StringBuffer();
833                 ret.append("(");
834                 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
835                 ret.append(")");
836                 return ret.toString();
837             }
838             static String flags(Mailbox.Iterator it) {
839                 return
840                     ((it.getFlags() & Mailbox.Flag.DELETED)!=0  ? "\\Deleted "  : "") +
841                     ((it.getFlags() & Mailbox.Flag.SEEN)!=0     ? "\\Seen "     : "") +
842                     ((it.getFlags() & Mailbox.Flag.FLAGGED)!=0  ? "\\Flagged "  : "") +
843                     ((it.getFlags() & Mailbox.Flag.DRAFT)!=0    ? "\\Draft "    : "") +
844                     ((it.getFlags() & Mailbox.Flag.ANSWERED)!=0 ? "\\Answered " : "") +
845                     ((it.getFlags() & Mailbox.Flag.RECENT)!=0   ? "\\Recent "   : "");
846         }
847         static String flags(int flags) {
848             String ret = "(" +
849                 (((flags & Mailbox.Flag.DELETED) == Mailbox.Flag.DELETED) ? "\\Deleted "  : "") +
850                 (((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN)    ? "\\Seen "     : "") +
851                 (((flags & Mailbox.Flag.FLAGGED) == Mailbox.Flag.FLAGGED) ? "\\Flagged "  : "") +
852                 (((flags & Mailbox.Flag.DRAFT) == Mailbox.Flag.DRAFT)   ? "\\Draft "    : "") +
853                 (((flags & Mailbox.Flag.ANSWERED) == Mailbox.Flag.ANSWERED)? "\\Answered " : "") +
854                 (((flags & Mailbox.Flag.RECENT) == Mailbox.Flag.RECENT)  ? "\\Recent "   : "");
855             if (ret.endsWith(" ")) ret = ret.substring(0, ret.length() - 1);
856             return ret + ")";
857         }
858         static String bodystructure(Message m) {
859             // FIXME
860             return "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"ISO-8859-1\") NIL NIL \"7BIT\" "+m.getLength()+" "+m.getNumLines()+")";
861         }
862         static String message(Message m) { return m.toString(); }
863         static String date(Date d) { return "\""+d.toString()+"\""; }
864         static String envelope(Message m) {
865             return
866                 "(" + quotify(m.arrival.toString()) +
867                 " " + quotify(m.subject) +          
868                 " " + addressList(m.from) +      
869                 " " + addressList(m.headers.get("sender")) +
870                 " " + addressList(m.replyto) + 
871                 " " + addressList(m.to) + 
872                 " " + addressList(m.cc) + 
873                 " " + addressList(m.bcc) + 
874                 " " + quotify((String)m.headers.get("in-reply-to")) +
875                 " " + quotify(m.messageid) +
876                 ")";
877         }
878         
879         // FIXME: ugly
880         public static String qq(Stream stream) {
881             StringBuffer sb = new StringBuffer();
882             stream.transcribe(sb);
883             return qq(sb.toString());
884         }
885         public static String qq(String s) {
886             StringBuffer ret = new StringBuffer();
887             ret.append('{');
888             ret.append(s.getBytes().length);
889             ret.append('}');
890             ret.append('\r');
891             ret.append('\n');
892             ret.append(s);
893             return ret.toString();
894         }
895         
896         private static String join(int[] nums) {
897             StringBuffer ret = new StringBuffer();
898             for(int i=0; i<nums.length; i++) {
899                 ret.append(nums[i]);
900                 if (i<nums.length-1) ret.append(' ');
901             }
902             return ret.toString();
903         }
904         private static String join(String delimit, String[] stuff) {
905             StringBuffer ret = new StringBuffer();
906             for(int i=0; i<stuff.length; i++) {
907                 ret.append(stuff[i]);
908                 if (i<stuff.length - 1) ret.append(delimit);
909             }
910             return ret.toString();
911         }
912         }
913
914
915     // Main //////////////////////////////////////////////////////////////////////////////
916
917     public static final int
918         PEEK=0x1, BODYSTRUCTURE=0x2, ENVELOPE=0x4, FLAGS=0x8, INTERNALDATE=0x10, FIELDS=0x800, FIELDSNOT=0x1000,
919         RFC822=0x20, RFC822TEXT=0x40, RFC822SIZE=0x80, HEADERNOT=0x100, UID=0x200, HEADER=0x400;
920 }