X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=src%2Forg%2Fibex%2Fmail%2Fprotocol%2FIMAP.java;h=c84fa78efe9dbdfb669a6fea9e29932417ba646c;hb=7cdf4460730a221d605aa93f95c27538d3eb2cb6;hp=21e937a8f6c150de5a80d816e9015b39d79acd3e;hpb=3bb3725cc8cd583b54936dd098081b13d7ff6e4c;p=org.ibex.mail.git diff --git a/src/org/ibex/mail/protocol/IMAP.java b/src/org/ibex/mail/protocol/IMAP.java index 21e937a..c84fa78 100644 --- a/src/org/ibex/mail/protocol/IMAP.java +++ b/src/org/ibex/mail/protocol/IMAP.java @@ -1,4 +1,11 @@ +// Copyright 2000-2005 the Contributors, as shown in the revision logs. +// Licensed under the Apache Public Source License 2.0 ("the License"). +// You may not use this file except in compliance with the License. + package org.ibex.mail.protocol; +import org.ibex.io.*; +import org.ibex.crypto.*; +import org.ibex.jinetd.Listener; import org.ibex.mail.*; import org.ibex.util.*; import org.ibex.mail.target.*; @@ -6,6 +13,11 @@ import java.util.*; import java.net.*; import java.text.*; import java.io.*; + +// FIXME: this is valid LSUB "" asdfdas%*%*%*%*SFEFGWEF +// FIXME: be very careful about where/when we quotify stuff +// FIXME: 'UID FOO 100:*' must match at least one message even if all UIDs less than 100 +// FIXME: LIST should return INBOX if applicable // Relevant RFC's: // RFC 2060: IMAPv4 @@ -13,92 +25,133 @@ import java.io.*; // RFC 3691: UNSELECT // RFC 2971: ID +// FEATURE: make sure we're being case-insensitive enough; probably want to upcase atom() +// FEATURE: MIME-queries and BODYSTRUCTURE // FEATURE: READ-WRITE / READ-ONLY status on SELECT // FEATURE: pipelining // FEATURE: support [charset] // FEATURE: \Noselect // FEATURE: subscriptions -public class IMAP extends MessageProtocol { +// FEATURE: tune for efficiency +// FEATURE: STARTTLS +// FEATURE: asynchronous client notifications (need to re-read RFC) - // Constants ////////////////////////////////////////////////////////////////////////////// +public class IMAP { - public static final char imapSeparator = '.'; - public static final float version = (float)0.1; + public IMAP() { } + public static final float version = (float)0.2; + // FIXME this is evil + public static String getBodyString(Message m) { + StringBuffer sb = new StringBuffer(); + m.getStream().transcribe(sb); + return sb.toString(); + } - // Callbacks ////////////////////////////////////////////////////////////////////////////// + // API Class ////////////////////////////////////////////////////////////////////////////// - public static interface Authenticator { public abstract Mailbox authenticate(String user, String pass); } + public static interface Client { + public void expunge(int uid); + public void list(char separator, String mailbox, boolean lsub, boolean phantom); + public void fetch(int num, int flags, int size, Message m, int muid); // m may be null or incomplete + } + public static interface Server { + public void setClient(IMAP.Client client); + public String[] capability(); + public Hashtable id(Hashtable clientId); + public void copy(Query q, String to); + public void logout(); + public void unselect(); + public void delete(String m); + public void create(String m); + public void append(String m, int flags, Date arrival, String body); + public void check(); + public void noop(); + public void close(); + public void subscribe(String mailbox); + public void unsubscribe(String mailbox); + public int unseen(String mailbox); + public int recent(String mailbox); + public int count(String mailbox); + public int count(); + public int maxuid(); + public int uidNext(String mailbox); + public int uidValidity(String mailbox); + public int[] search(Query q, boolean uid); + public void rename(String from, String to); + public void select(String mailbox, boolean examineOnly); + public void setFlags(Query q, int flags, boolean uid, boolean silent); + public void removeFlags(Query q, int flags, boolean uid, boolean silent); + public void addFlags(Query q, int flags, boolean uid, boolean silent); + public void expunge(); + public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid); + public void lsub(String start, String ref); + public void list(String start, String ref); + public static class Exn extends MailException { public Exn(String s) { super(s); } } + public static class Bad extends Exn { public Bad(String s) { super(s); } } + public static class No extends Exn { public No(String s) { super(s); } } + } - // Exceptions ////////////////////////////////////////////////////////////////////////////// - public static class Exn extends MailException { public Exn(String s) { super(s); } } - public static class Bad extends Exn { public Bad(String s) { super(s); } } - public static class No extends Exn { public No(String s) { super(s); } } + // MailboxWrapper ////////////////////////////////////////////////////////////////////////////// + /** wraps an IMAP.Server interface around a Mailbox */ + public static class MailboxWrapper implements Server { - // Single Session Handler ////////////////////////////////////////////////////////////////////////////// + public static final char sep = '.'; - private static class Session extends Incoming { + Mailbox inbox = null; Mailbox selected = null; + Mailbox root = null; Mailbox selected() { if (selected == null) throw new Bad("no mailbox selected"); return selected; } - String selectedName = null; - Mailbox inbox = null; - final Mailbox root; - final Socket conn; - final String vhost; - final Authenticator auth; - final PrintWriter pw; - final PushbackReader r; - final InputStream is; - public void init() { } - public Session(Socket conn, Mailbox root, Authenticator auth) throws IOException { - this(conn, java.net.InetAddress.getLocalHost().getHostName(), root, auth); } - public Session(Socket conn, String vhost, Mailbox root, Authenticator auth) throws IOException { - this.vhost = vhost; this.conn = conn; this.root = root; this.auth = auth; - this.pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream())); - this.r = new PushbackReader(new InputStreamReader(this.is = conn.getInputStream())); - } + final Login auth; + final Client client; - private void star(String s) { println("* " + s); } - private void println(String s) { pw.println(s); pw.flush(); } - private void print(String s) { pw.print(s); } + public MailboxWrapper(Login auth, Client c) { this.auth=auth; this.client=c;} + public void setClient(IMAP.Client client) { } - private Mailbox getMailbox(String name, boolean create) { + private Mailbox mailbox(String name, boolean create) { return mailbox(name, create, true); } + private Mailbox mailbox(String name, boolean create, boolean throwexn) { + if (name.equalsIgnoreCase("inbox")) return inbox; Mailbox m = root; - for(StringTokenizer st = new StringTokenizer(name, imapSeparator + ""); st.hasMoreTokens();) - if ((m = m.slash(st.nextToken(), create)) == null) throw new No("no such mailbox " + name); + for(StringTokenizer st = new StringTokenizer(name, sep + ""); st.hasMoreTokens();) + if ((m = m.slash(st.nextToken(), create)) == null) { + if (throwexn) throw new Server.No("no such mailbox " + name); + return null; + } return m; } // FEATURE: not accurate when a wildcard and subsequent non-wildcards both match a single component - public HashSet lsub(String start, String ref, HashSet reply) { return list(start, ref, reply); } - public HashSet list(String start, String ref, HashSet reply) { - if (reply == null) reply = new HashSet(); - if (ref.length() == 0 && start.length() == 0) { reply.add(""); return reply; } - while (start.endsWith(""+imapSeparator)) start = start.substring(0, start.length() - 1); - String[] children = (start.length() == 0 ? root : getMailbox(start, false)).children(); + public void lsub(String start, String ref) { list(start, ref, true); } + public void list(String start, String ref) { list(start, ref, false); } + public void list(String start, String ref, boolean lsub) { + if (ref.length() == 0) { client.list(sep, start, lsub, false); return; } + while (start.endsWith(""+sep)) start = start.substring(0, start.length() - 1); + if (ref.endsWith("%")) ref = ref + sep; + String[] children = (start.length() == 0 ? root : mailbox(start, false)).children(); for(int i=0; i 0 ? imapSeparator+"" : "") + s; + String s = children[i], pre = ref, kid = start + (start.length() > 0 ? sep+"" : "") + s; + if (mailbox(kid, false) == null) continue; + boolean phantom = mailbox(kid, false).phantom(); while(true) { if (pre.length() == 0) { - if (s.length() == 0) reply.add(kid); + if (s.length() == 0) client.list(sep, kid, lsub, phantom); } else switch(pre.charAt(0)) { - case imapSeparator: if (s.length() == 0) list(kid, pre.substring(1), reply); break; - case '%': reply.add(kid); pre=pre.substring(1); list(kid, pre, reply); break; - case '*': reply.add(kid); list(kid, pre, reply); pre = pre.substring(1); break; - default: if (s.length()==0) break; - if (s.charAt(0) != pre.charAt(0)) break; - s = s.substring(1); pre = pre.substring(1); continue; + case sep: if (s.length() == 0) list(kid, pre.substring(1), lsub); break; + case '%': client.list(sep,kid,lsub,phantom);pre=pre.substring(1); s = ""; continue; + case '*': client.list(sep,kid,lsub,phantom);list(kid,pre,lsub);pre=pre.substring(1); break; + default: if (s.length()==0) break; + if (s.charAt(0) != pre.charAt(0)) break; + s = s.substring(1); pre = pre.substring(1); continue; } break; } } - return reply; } - public String[] capability() { return new String[] { "IMAP4rev1", "UNSELECT", "ID" }; } + public String[] capability() { return new String[] { "IMAP4rev1" , "UNSELECT", "ID" }; } public Hashtable id(Hashtable clientId) { Hashtable response = new Hashtable(); response.put("name", IMAP.class.getName()); @@ -110,239 +163,481 @@ public class IMAP extends MessageProtocol { return response; } - public void copy(Query q, Mailbox to) { for(Mailbox.Iterator it=selected.iterator(q);it.next();) to.add(it.cur()); } - public void login(String u, String p) { if ((inbox = auth.authenticate(u,p)) == null) throw new No("Login failed."); } - public void logout() { } - public void unselect() { selected = null; selectedName = null; } - public void delete(Mailbox m) { if (!m.equals(inbox)) m.destroy(); } - public void create(String m) { if (!m.endsWith(""+imapSeparator) && !m.equalsIgnoreCase("inbox")) getMailbox(m, true); } - public void append(Mailbox m, int flags, Date arrival, String body) { m.add(new Message(null,null,body,arrival), flags); } + public void copy(Query q, String to) { copy(q, mailbox(to, false)); } + /* */ void copy(Query q, Mailbox to) { + for(Mailbox.Iterator it=selected().iterator(q);it.next();) to.add(it.cur(), it.flags() | Mailbox.Flag.RECENT); } + + public void unselect() { selected = null; } + public void delete(String m0) { delete(mailbox(m0,false)); } + public void delete(Mailbox m) { if (!m.equals(inbox)) m.destroy(false); else throw new Bad("can't delete inbox"); } + public void create(String m) { mailbox(m, true, false); } + public void append(String m,int f,Date a,String b) { try { + mailbox(m,false).add(Message.newMessage(new Fountain.StringFountain(b)),f|Mailbox.Flag.RECENT); + } catch (Message.Malformed e) { throw new No(e.getMessage()); } } public void check() { } public void noop() { } - public void close() { for(Mailbox.Iterator it=selected().iterator(Query.deleted()); it.next();) it.delete(); unselect(); } - public void expunge() { for(Mailbox.Iterator it = selected().iterator(Query.deleted()); it.next();) expunge(it); } - public void expunge(Mailbox.Iterator it) { star(it.uid() + " EXPUNGE"); it.delete(); } + public void logout() { } + public void close() { for(Mailbox.Iterator it=selected().iterator(Query.deleted()); it.next();) it.delete(); } + public void expunge() { for(Mailbox.Iterator it = selected().iterator(Query.deleted());it.next();) expunge(it); } + public void expunge(Mailbox.Iterator it) { client.expunge(it.uid()); it.delete(); } public void subscribe(String mailbox) { } public void unsubscribe(String mailbox) { } - public int seen(String mailbox) { return getMailbox(mailbox, false).count(Query.seen()); } - public int recent(String mailbox) { return getMailbox(mailbox, false).count(Query.recent()); } - public int count(String mailbox) { return getMailbox(mailbox, false).count(Query.all()); } - public int uidNext(String mailbox) { return getMailbox(mailbox, false).uidNext(); } - public int uidValidity(String mailbox) { return getMailbox(mailbox, false).uidValidity(); } - public void rename(Mailbox from, String to) { - if (from.equals(inbox)) from.copy(Query.all(), getMailbox(to, true)); - else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), getMailbox(to, true)); from.destroy(); } - else from.rename(to); + public int maxuid() { + int ret = 0; + Mailbox mb = selected(); + if (mb == null) return 0; + for(Mailbox.Iterator it = mb.iterator(); it.next(); ) ret = it.uid(); + return ret; } - + public int unseen(String mailbox) { return mailbox(mailbox, false).count(Query.not(Query.seen())); } + public int recent(String mailbox) { return mailbox(mailbox, false).count(Query.recent()); } + public int count(String mailbox) { return mailbox(mailbox, false).count(Query.all()); } + public int count() { return selected().count(Query.all()); } + public int uidNext(String mailbox) { return mailbox(mailbox, false).uidNext(); } + public int uidValidity(String mailbox) { return mailbox(mailbox, false).uidValidity(); } public void select(String mailbox, boolean examineOnly) { - selected = getMailbox(selectedName = mailbox, false); - star("FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)"); - star(selected.count(Query.all()) + " EXISTS"); - star(selected.count(Query.recent()) + " RECENT"); - star("OK [UIDVALIDITY " + selected.uidValidity() + "] UIDs valid"); + selected = mailbox(mailbox, false); + } + + public int[] search(Query q, boolean uid) { + Vec.Int vec = new Vec.Int(); + for(Mailbox.Iterator it = selected().iterator(q); it.next();) { + vec.addElement(uid ? it.uid() : it.num()); + it.recent(false); + } + return vec.dump(); } - // uber FIXME - public void fetch(Query q, FetchRequest[] fr, boolean uid) { - for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) { - Message m = it.cur(); - StringBuffer reply = new StringBuffer(); - boolean peek = false; - for(int i=0; i" + qq(payload.substring(0, frb.end + 1))); - else reply.append("<" + frb.start + "." + frb.end + ">" + qq(payload.substring(frb.start, frb.end + 1))); - } else throw new Error("this should never happen"); - star((uid ? it.uid() : it.num()) + " FETCH (" + reply.toString() + (uid ? " UID " + it.uid() : "") + ")"); - if (!peek) it.seen(true); + public void setFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, 0, silent); } + public void addFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, 1, silent); } + public void removeFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, -1, silent); } + + private void doFlags(Query q, int flags, boolean uid, int style, boolean silent) { + for(Mailbox.Iterator it = selected().iterator(q);it.next();) { + boolean recent = it.recent(); + try { throw new Exception("flags " + flags); } catch (Exception e) { Log.error(this, e); } + if (style == -1) it.removeFlags(flags); + else if (style == 0) it.setFlags(flags); + else if (style == 1) it.addFlags(flags); + it.recent(recent); + if (!silent) client.fetch(it.num(), it.flags(), -1, null, it.uid()); } + } + public void rename(String from0, String to) { + Mailbox from = mailbox(from0, false); + if (from.equals(inbox)) { from.copy(Query.all(), mailbox(to, true)); } + else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), mailbox(to, true)); from.destroy(false); } + else from.rename(to); } + public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid) { + for(Mailbox.Iterator it = selected().iterator(q); it.next(); ) { + Message message = ((spec & (BODYSTRUCTURE | ENVELOPE | INTERNALDATE | FIELDS | FIELDSNOT | RFC822 | + RFC822TEXT | RFC822SIZE | HEADERNOT | HEADER)) != 0) ? it.cur() : null; + int size = message == null ? 0 : message.getLength(); + client.fetch(it.num(), it.flags(), size, message, it.uid()); + it.recent(false); + } + } + } - public void store(Query q, int addFlags, int removeFlags, boolean silent, boolean uid) { - for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) { - it.addFlags(addFlags); - it.removeFlags(removeFlags); - if (!silent) star((uid ? it.uid() : it.num()) + " FETCH (FLAGS (" + flags(it) + "))"); + + // Single Session Handler ////////////////////////////////////////////////////////////////////////////// + + /** takes an IMAP.Server and exposes it to the world as an IMAP server on a TCP socket */ + public static class Listener implements Client { + String selectedName = null; + Mailbox inbox = null, root = null; + Server api; + Parser parser = null; + Connection conn = null; + Login auth; + public Listener(Login auth) { api = new IMAP.MailboxWrapper(this.auth = auth, this); } + Parser.Token token() { return parser.token(); } + void println(String s) { conn.println(s); } + void newline() { parser.newline(); } + Query query(int max) { return parser.query(max, maxn(true)); } + + public void login(String u, String p) { + Object ret; + if ((ret = auth.login(u,p,IMAP.class)) == null) throw new Server.No("Login failed."); + if (ret instanceof IMAP.Server) { + api = (IMAP.Server)ret; + api.setClient(this); + } else { + Account account = (Account)ret; + ((MailboxWrapper)api).root = root = account.getMailbox(IMAP.class); + Log.warn(this, "logged in, root="+root); + ((MailboxWrapper)api).inbox = inbox = root.slash("INBOX", false); + if (inbox == null) ((MailboxWrapper)api).inbox = inbox = root; } } - private void emitListResponse(HashSet boxes) - { for(Iterator it = boxes.iterator(); it.hasNext(); ) star("LIST \"" + imapSeparator + "\" \"" + it.next() + "\""); } + private int maxn(boolean uid) { return uid ? api.maxuid() : api.count(); } - public boolean handleRequest() throws IOException { - println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4rev1 [RFC3501] v" + version + " server ready"); + public void handleRequest(Connection conn) { + this.conn = conn; + parser = new Parser(conn); + conn.setTimeout(30 * 60 * 1000); + println("* OK " + conn.vhost + " " + IMAP.class.getName() + " IMAP4rev1 [RFC3501] v" + version + " server ready"); for(String tag = null;; newline()) try { - pw.flush(); + conn.flush(); boolean uid = false; - tag = null; tag = token().atom(); + tag = null; Parser.Token tok = token(); if (tok == null) return; tag = tok.astring(); String command = token().atom(); - if (command.equals("UID")) { uid = true; command = token().atom(); } - switch(((Integer)commands.get(command.toUpperCase())).intValue()) { - case AUTHENTICATE: login(token().astring(), token().astring()); break; - case LIST: emitListResponse(list(token().q(), token().q(), null)); break; - case LSUB: emitListResponse(lsub(token().q(), token().q(), null)); break; - case SUBSCRIBE: subscribe(token().atom()); break; - case UNSUBSCRIBE: unsubscribe(token().atom()); break; - case CAPABILITY: star("CAPABILITY " + join(" ", capability())); break; - //case ID: id(); break; + if (command.equalsIgnoreCase("UID")) { uid = true; command = token().atom(); } + int commandKey = ((Integer)commands.get(command.toUpperCase())).intValue(); + switch(commandKey) { case LOGIN: login(token().astring(), token().astring()); break; - case LOGOUT: logout(); star("BYE"); conn.close(); return false; - case RENAME: rename(token().mailbox(), token().atom()); break; - case EXAMINE: select(token().astring(), true); break; - case SELECT: select(token().astring(), false); break; - case COPY: copy(Query.set(uid, token().set()), token().mailbox()); break; - case DELETE: delete(token().mailbox()); break; - case CHECK: check(); break; - case NOOP: noop(); break; - case CLOSE: close(); break; - case EXPUNGE: expunge(); break; - case UNSELECT: unselect(); break; - case CREATE: create(token().astring()); break; - case FETCH: fetch(Query.set(uid, token().set()), parseFetch(token().l()), uid); break; + case CAPABILITY: println("* CAPABILITY " + Printer.join(" ", api.capability())); break; + case AUTHENTICATE: throw new Server.No("AUTHENTICATE not supported"); + case LOGOUT: api.logout(); println("* BYE"); conn.close(); return; + case LIST: api.list(token().q(), token().astring()); break; /*astring is a hack for EUDORA*/ + case LSUB: api.lsub(token().q(), token().q()); break; + case SUBSCRIBE: api.subscribe(token().astring()); break; + case UNSUBSCRIBE: api.unsubscribe(token().astring()); break; + case RENAME: api.rename(token().astring(), token().astring()); break; + case COPY: selected(); api.copy(Query.set(uid, token().set(maxn(uid))), token().astring()); break; + case DELETE: api.delete(token().atom()); break; + case CHECK: selected(); api.check(); break; + case NOOP: api.noop(); break; + case CLOSE: selected(); api.close(); break; + case EXPUNGE: selected(); api.expunge(); break; + case UNSELECT: selected(); api.unselect(); selected = false; break; + case CREATE: api.create(token().astring()); break; + case FETCH: selected(); fetch(Query.set(lastuid=uid, token().set(maxn(uid))), + lastfetch=token().lx(), 0, 0, 0, uid, 0); break; + case SEARCH: { + selected(); + int[] result = api.search(query(maxn(uid)), uid); + /*if (result.length > 0)*/ println("* SEARCH " + Printer.join(result)); + break; + } + case EXAMINE: + case SELECT: { + String mailbox = token().astring(); + api.select(mailbox, commandKey==EXAMINE); + println("* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)"); + println("* " + api.count(mailbox) + " EXISTS"); + println("* " + api.recent(mailbox) + " RECENT"); + println("* OK [UNSEEN " + api.unseen(mailbox) + "]"); + println("* OK [UIDVALIDITY " + api.uidValidity(mailbox) + "] UIDs valid"); + println("* OK [UIDNEXT " + api.uidNext(mailbox) + "]"); + println("* OK [PERMANENTFLAGS (\\Seen)]"); + selected = true; + break; } case STATUS: { - String mailbox = token().atom(); - Token[] list = token().l(); + String mailbox = token().astring(); // hack for GNUS buggy client + Parser.Token[] list = token().l(); String response = ""; for(int i=0; i0) response += " "; + if (s.equals("MESSAGES")) response += "MESSAGES " + api.count(mailbox); + if (s.equals("RECENT")) response += "RECENT " + api.recent(mailbox); + if (s.equals("UIDNEXT")) response += "UIDNEXT " + api.uidNext(mailbox); + if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + api.uidValidity(mailbox); + if (s.equals("UNSEEN")) response += "UNSEEN " + api.unseen(mailbox); } - star("STATUS " + selectedName + " (" + response + ")"); + println("* STATUS " + mailbox + " (" + response + ")"); + break; } case APPEND: { - Mailbox m = token().mailbox(); + String m = token().astring(); int flags = 0; - Date arrival = null; - Token t = token(); + Date arrival = new Date(); + Parser.Token t = token(); if (t.type == t.LIST) { flags = t.flags(); t = token(); } - if (t.type == t.QUOTED) { arrival = t.datetime(); t = token(); } - append(m, flags, arrival, token().q()); + if (t.type != t.QUOTED) { arrival = t.datetime(); t = token(); } + api.append(m, flags, arrival, t.q()); break; } case STORE: { - Query q = uid ? Query.uid(token().set()) : Query.num(token().set()); - String s = token().atom(); + selected(); + Query q = uid ? Query.uid(token().set(maxn(uid))) : Query.num(token().set(maxn(uid))); + String s = token().atom().toUpperCase(); int flags = token().flags(); - if (s.equals("FLAGS")) store(q, flags, ~flags, false, uid); - else if (s.equals("+FLAGS")) store(q, flags, 0, false, uid); - else if (s.equals("-FLAGS")) store(q, 0, flags, false, uid); - else if (s.equals("FLAGS.SILENT")) store(q, flags, ~flags, true, uid); - else if (s.equals("+FLAGS.SILENT")) store(q, flags, 0, true, uid); - else if (s.equals("-FLAGS.SILENT")) store(q, 0, flags, true, uid); - else throw new Bad("unknown STORE specifier " + s); + if (s.equals("FLAGS")) api.setFlags(q, flags, uid, false); + else if (s.equals("+FLAGS")) api.addFlags(q, flags, uid, false); + else if (s.equals("-FLAGS")) api.removeFlags(q, flags, uid, false); + else if (s.equals("FLAGS.SILENT")) api.setFlags(q, flags, uid, true); + else if (s.equals("+FLAGS.SILENT")) api.addFlags(q, flags, uid, true); + else if (s.equals("-FLAGS.SILENT")) api.removeFlags(q, flags, uid, true); + else throw new Server.Bad("unknown STORE specifier " + s); break; } - default: throw new Bad("unrecognized command \"" + command + "\""); + default: throw new Server.Bad("unrecognized command \"" + command + "\""); } - println(tag + " OK " + command + " Completed."); - } catch (Bad b) { println(tag==null ? "* BAD Invalid tag" : (tag + " Bad " + b.toString())); b.printStackTrace(); - } catch (No n) { println(tag==null ? "* BAD Invalid tag" : (tag + " No " + n.toString())); n.printStackTrace(); } + println(tag+" OK "+command+" Completed. " + + (commandKey == LOGIN ? ("[CAPABILITY "+Printer.join(" ", api.capability())+"]") : "")); + Log.error("[imap]", conn.dumpLog()); + } catch (Server.Bad b) { println(tag==null ? "* BAD Invalid tag":(tag + " Bad " + b.toString())); + } catch (Server.No n) { println(tag==null?"* BAD Invalid tag":(tag+" No " + n.toString())); } } - Query query() { + private Parser.Token[] lastfetch = null; // hack + private boolean lastuid = false; // hack + private boolean selected = false; + private void selected() { if (!selected) throw new Server.Bad("no mailbox selected"); } + + // Callbacks ////////////////////////////////////////////////////////////////////////////// + + public void expunge(int uid) { println("* " + uid + " EXPUNGE"); } + public void fetch(int n, int f, int size, Message m, int muid) { fetch(m, lastfetch, n, f, size, lastuid, muid); } + public void list(char sep, String mb, boolean sub, boolean p) { + println("* " + (sub?"LSUB":"LIST")+" ("+(p?"\\Noselect":"")+") \""+sep+"\" \""+mb+"\"");} + + /** + * Parse a fetch request or emit a fetch reply. + * + * To avoid duplicating tedious parsing logic, this function + * performs both of the following tasks: + * - parse the fetch request in Token[] t and return a fetch spec + * - emit a fetch reply for the parsed spec with respect to message m + */ + private void fetch(Object o, Parser.Token[] t, int num, int flags, int size, boolean uid, int muid) { + Query q = o == null ? null : o instanceof Query ? (Query)o : null; + Message m = o == null ? null : o instanceof Message ? (Message)o : null; + boolean e = q == null; + + // asynchronous flags update + if (size == -1) { + println("* " + num + " FETCH (FLAGS " + Printer.flags(flags) + (uid?(" UID "+muid):"") + ")"); + return; + } + + lastfetch = t; + int spec = 0; // spec; see constants for flags + String[] headers = null; + int start = -1, end = -1; + StringBuffer r = new StringBuffer(); + if (e) { r.append(num); r.append(" FETCH ("); } + int initlen = r.length(); + if (uid) { + boolean good = false; + for(int i=0; i initlen) r.append(" "); + if (t[i] == null || t[i].s == null) continue; + String s = t[i].s.toUpperCase(); + r.append(s.equalsIgnoreCase("BODY.PEEK")?"BODY":s); + if (s.equals("BODYSTRUCTURE")) { spec|=BODYSTRUCTURE;if(e){r.append(" ");r.append(Printer.bodystructure(m));} + } else if (s.equals("ENVELOPE")) { spec|=ENVELOPE; if(e){r.append(" ");r.append(Printer.envelope(m));} + } else if (s.equals("FLAGS")) { spec|=FLAGS; if(e){r.append(" ");r.append(Printer.flags(flags));} + } else if (s.equals("INTERNALDATE")) { spec|=INTERNALDATE; if(e){r.append(" ");r.append(Printer.date(m.arrival));} + } else if (s.equals("RFC822")) { spec|=RFC822; if(e){r.append(" ");r.append(Printer.message(m));} + } else if (s.equals("RFC822.TEXT")) { spec|=RFC822TEXT; if(e){r.append(" ");r.append(Printer.qq(getBodyString(m)));} + } else if (s.equals("RFC822.HEADER")){ spec|=HEADER;if(e){r.append(" ");r.append(Printer.qq(m.headers.getString()+"\r\n"));} + } else if (s.equals("RFC822.SIZE")) { spec|=RFC822SIZE; if(e){r.append(" ");r.append(m.getLength());} + } else if (s.equals("UID")) { spec|=UID; if(e){r.append(" ");r.append(muid); } + } else if (!(s.equals("BODY.PEEK") || s.equals("BODY"))) { throw new Server.No("unknown fetch argument: " + s); + } else { + if (s.equalsIgnoreCase("BODY.PEEK")) spec |= PEEK; + //else if (e) api.addFlags(Query.num(new int[] { num, num }), Mailbox.Flag.SEEN, false, false); + if (i >= t.length - 1 || t[i+1].type != Parser.Token.LIST) { + spec |= BODYSTRUCTURE; + if (e) { r.append(" "); r.append(Printer.bodystructure(m)); } continue; + //{ if (e) { r.append(" "); r.append(Printer.qq(m.body)); } continue; } + } + String payload = ""; + r.append("["); + Parser.Token[] list = t[++i].l(); + s = list.length == 0 ? "" : list[0].s.toUpperCase(); + r.append(s); + if (list.length == 0) { spec |= RFC822TEXT; if(e) payload = m.headers.getString()+"\r\n"+getBodyString(m); } + else if (s.equals("") || s.equals("1")) { spec |= RFC822TEXT; if(e) payload = m.headers.getString()+"\r\n"+getBodyString(m); } + else if (s.equals("TEXT")) { spec |= RFC822TEXT; if(e) payload = getBodyString(m); } + else if (s.equals("HEADER")) { spec |= HEADER; if(e) payload = m.headers.getString()+"\r\n"; } + else if (s.equals("HEADER.FIELDS")) { spec |= FIELDS; payload=headers(r,t[i].l()[1].sl(),false,m,e); } + else if (s.equals("HEADER.FIELDS.NOT")) { spec |= FIELDSNOT; payload=headers(r,t[i].l()[1].sl(),true,m,e); } + else if (s.equals("MIME")) { throw new Server.Bad("MIME not supported"); } + else throw new Server.Bad("unknown section type " + s); + if (i')); + int dot = s.indexOf('.'); + start = dot == -1 ? Integer.parseInt(s) : Integer.parseInt(s.substring(0, s.indexOf('.'))); + end = dot == -1 ? -1 : Integer.parseInt(s.substring(s.indexOf('.') + 1)); + if (e) { payload = payload.substring(start, Math.min(end+1,payload.length())); r.append("<"+start+">"); } + } + if (e) { r.append("] "); r.append(Printer.qq(payload)); } + } + } + if (e) { + r.append(")"); + println("* " + r.toString()); + } else { + api.fetch(q, spec, headers, start, end, uid); + } + } + + private String headers(StringBuffer r, String[] headers, boolean negate, Message m, boolean e) { + String payload = ""; + if (e) r.append(" ("); + if (!negate) { + if(e) for(int j=0; j")) { - startend = s.substring(s.indexOf('<'), s.indexOf('>')); - s = s.substring(0, s.indexOf('<')); - } - - if (s.equalsIgnoreCase("BODY.PEEK")) b.peek = true; - else if (s.equalsIgnoreCase("BODY")) b.peek = false; - else throw new No("unknown fetch argument: " + s); - - if (i= '0' && s2.charAt(0) <= '9') { - mimeVec.addElement(new Integer(Integer.parseInt(s2.substring(0, s2.indexOf('.'))))); - s2 = s2.substring(s2.indexOf('.') + 1); - } - if (mimeVec.size() > 0) { - b.path = new int[mimeVec.size()]; - for(int j=0; j