package org.ibex.mail.protocol;
+import org.ibex.io.*;
+import org.ibex.jinetd.Listener;
+import org.ibex.jinetd.Worker;
+import org.ibex.mail.*;
+import org.ibex.util.*;
+import org.ibex.mail.target.*;
+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
+// RFC 3501: IMAPv4 with clarifications
+// 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]
-public class IMAP extends MessageProtocol {
+// FEATURE: \Noselect
+// FEATURE: subscriptions
+// FEATURE: tune for efficiency
+// FEATURE: STARTTLS
+// FEATURE: asynchronous client notifications (need to re-read RFC)
- public static void main(String[] args) throws Exception {
- ServerSocket ss = new ServerSocket(143);
- while(true) {
- System.out.println("listening");
- final Socket s = ss.accept();
- System.out.println("connected");
- new Thread() {
- public void run() {
- try {
- service(s);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }.start();
- }
+public class IMAP {
+
+ public IMAP() { }
+ public static final float version = (float)0.1;
+
+ // API Class //////////////////////////////////////////////////////////////////////////////
+
+ 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
}
- private static class Listener extends Incoming {
- Socket conn;
- String vhost;
+ public static interface Server {
+ public String[] capability();
+ public Hashtable id(Hashtable clientId);
+ public void copy(Query q, String to);
+ public void login(String u, String p);
+ 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 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 interface Authenticator { public abstract Mailbox authenticate(String user, String pass); }
+ 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 {
+
+ public static final char sep = '.';
+
+ Mailbox inbox = null;
Mailbox selected = null;
- public void init() { }
- public Listener(Socket conn, String vhost) { this.vhost = vhost; this.conn = conn; this.selected = null; }
-
- public void login(String user, String password) { if (!auth(user, password)) throw new No("Liar, liar, pants on fire."); }
- public void capability() { star("CAPABILITY IMAP4rev1"); ok("Completed"); }
- public void noop() { ok("Completed"); }
- public void logout() { star("BYE LOGOUT received"); ok("Completed"); }
- public void delete(Mailbox m) { if (!m.getName().toLowerCase().equals("inbox")) m.delete(); }
- public void subscribe(String[] args) { ok("SUBSCRIBE ignored"); }
- public void unsubscribe(String[] args) { ok("UNSUBSCRIBE ignored"); }
- public void check(String[] args, boolean examineOnly) { ok("check complete"); }
- public void lsub(String[] args) { list(args); }
- public void list(String[] args) { star("LIST () \".\" INBOX"); ok("LIST completed"); }
- public void create(String mailbox) {
- if (mailbox.charAt(mailbox.length() - 1) != '.' &&
- !mailbox.toLowerCase.equals("inbox"))
- if (!storage.create(mailbox))
- throw No("unable to CREATE mailbox");
- ok("CREATE completed");
+ Mailbox root = null;
+ Mailbox selected() { if (selected == null) throw new Bad("no mailbox selected"); return selected; }
+ final Server.Authenticator auth;
+ final Client client;
+
+ public MailboxWrapper(Server.Authenticator auth, Client c) { this.auth=auth; this.client=c;}
+
+ private Mailbox mailbox(String name, boolean create) {
+ if (name.equalsIgnoreCase("inbox")) return inbox;
+ Mailbox m = root;
+ for(StringTokenizer st = new StringTokenizer(name, sep + ""); st.hasMoreTokens();)
+ if ((m = m.slash(st.nextToken(), create)) == null) throw new Server.No("no such mailbox " + name);
+ return m;
}
- public void rename(Mailbox from, String to) {
- if (from.getName().toLowerCase().equals("inbox")) {
- int[] messages = from.list();
- Malbox toBox = getMailbox(to);
- for(int i=0; i<messages.length; i++) {
- Message m = from.get(messages[i]);
- toBox.add(m);
- from.delete(messages[i]);
- }
- } else if (to.toLowerCase().equals("inbox")) {
- int[] messages = from.list();
- Mailbox inbox = getMailbox("inbox");
- for(int i=0; i<messages.length; i++) {
- Message m = from.get(messages[i]);
- inbox.add(m);
- from.delete(messages[i]);
+
+ // FEATURE: not accurate when a wildcard and subsequent non-wildcards both match a single component
+ 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<children.length; i++) {
+ String s = children[i], pre = ref, kid = start + (start.length() > 0 ? sep+"" : "") + s;
+ boolean phantom = mailbox(kid, false).phantom();
+ while(true) {
+ if (pre.length() == 0) {
+ if (s.length() == 0) client.list(sep, kid, lsub, phantom);
+ } else switch(pre.charAt(0)) {
+ 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;
}
- // FIXME delete from
- } else {
- from.rename(to);
}
}
- public void status(Mailbox mbox, boolean messages, boolean recent, boolean uidnext, boolean uidvalidity, boolean unseen) {
- for(int i=0; i<toks.length; i++) {
- if (toks[i].equals("MESSAGES")) messages = true;
- else if (toks[i].equals("RECENT")) recent = true;
- else if (toks[i].equals("UIDNEXT")) uidnext = true;
- else if (toks[i].equals("UIDVALIDITY")) uidvalidity = true;
- else if (toks[i].equals("UNSEEN")) unseen = true;
- }
- int[] messages = mbox.list();
- int numRecent = 0, numUnseen = 0;
- for(int i=0; i<messages.length; i++) {
- Message m = mbox.get(messages[i]);
- if (!m.seen) numUnseen++;
- if (m.recent) numRecent++;
- }
- star("STATUS " + args[0] + " (" +
- (messages ? ("MESSAGES " + messages.length + " ") : "") +
- (recent ? ("RECENT " + numRecent + " ") : "") +
- (unseen ? ("UNSEEN " + numUnseen + " ") : "") +
- (uidvalidity ? ("UIDVALIDITY " + mbox.uidvalidity + " ") : "") +
- (uidnext ? ("UIDNEXT " + mbox.uidnext + " ") : "") + ")");
- }
+ public String[] capability() { return new String[] { "IMAP4rev1" , "UNSELECT", "ID" }; }
+ public Hashtable id(Hashtable clientId) {
+ Hashtable response = new Hashtable();
+ response.put("name", IMAP.class.getName());
+ response.put("version", version + "");
+ response.put("os", System.getProperty("os.name", null));
+ response.put("os-version", System.getProperty("os.version", null));
+ response.put("vendor", "none");
+ response.put("support-url", "http://mail.ibex.org/");
+ return response;
+ }
- public void select(String[] args, boolean examineOnly) {
- if (args.length < 1) throw new Bad("Not enough arguments");
- selected = geMailbox(args[0]);
- if (selected == null) throw new No("No such mailbox");
- star("EXISTS");
- star("1 RECENT");
- star("OK [UNSEEN 12] Message 12 is first unseen");
- star("OK [UIDVALIDITY 123123123] UIDs valid");
- star("FLAGS (\Answered \Flagged \Deleted \Seen \Draft)");
- ok("[READ-WRITE] " + (examineOnly ? "EXAMINE" : "SELECT") + " completed");
- }
- public void close(String[] args, boolean examineOnly) {
- if (selected == null) throw new Bad("no mailbox selected");
- expunge(new String[] { }, false, true);
- selected = null;
- ok("CLOSE completed");
+ 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 login(String u, String p) {
+ if ((root = auth.authenticate(u,p)) == null) throw new No("Login failed.");
+ inbox = mailbox("INBOX", false); // FEATURE: ??
}
- public void expunge(String[] args, boolean examineOnly, boolean silent) {
- if (selected == null) throw new Bad("no mailbox selected");
- int[] messages = selected.list();
- for(int i=0; i<messages.length; i++) {
- Message m = selected.get(messages[i]);
- if (m.deleted) {
- if (!silent) star(m.uid + " EXPUNGE");
- if (!examineOnly) selected.delete(i);
- }
+ 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); }
+ public void append(String m,int f,Date a,String b) { try {
+ mailbox(m,false).add(new Message(null,null,b,a),f|Mailbox.Flag.RECENT);
+ } catch (Message.Malformed e) { throw new No(e.getMessage()); } }
+ public void check() { }
+ public void noop() { }
+ 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 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 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 = 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);
}
- if (!silent) ok("EXPUNGE completed");
+ return vec.dump();
}
- public void fetch(int[] messageSet, boolean examineOnly, boolean uid) {
- if (selected == null) throw new Bad("no mailbox selected");
- Object[] tokens = tokenize(args[0]);
- String[] headers;
- boolean negateHeaders;
- boolean flags;
- boolean internalDate;
- boolean size;
- boolean uid;
- int start, end;
- boolean setSeen;
- for(int i=0; i<tokens.length; i++) {
-
+ 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();
+ if (style == -1) it.removeFlags(flags);
+ else if (style == 0) it.setFlags(flags);
+ else if (style == 1) it.addFlags(flags);
+ it.recent(recent);
+ // FIXME
+ //if (!silent) client.fetch(it.num(), it.flags(), -1, null, it.uid());
}
- for(int i=0; i<messageSet.length; i++) {
- Message m = uid ? selected.getUID(messageSet[i]) : selected.get(messageSet[i]);
- fetch(m,
- String[] headers,
- boolean negateHeaders,
- boolean flags,
- boolean internalDate,
- boolean size,
- boolean uid,
- int start, int end,
- boolean setSeen);
- // FIXME
+ }
+ 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.size();
+ client.fetch(it.num(), it.flags(), size, message, it.uid());
+ it.recent(false);
}
}
+ }
- public void append(Mailbox m, Token flags, Date arrived, String literal) {
- Message m = new Message(null, null, new StringReader(literal));
- if (flags != null) flags.setFlags(m);
- if (arrived != null) m.arrival = arrived;
- selected.add(m);
- }
- public void copy(int[] set, Mailbox target) {
- for(int i=0; i<set.length; i++) {
- Message m = selected.get(set[i]);
- target.add(m); // sharing problem? immutability helps
- }
- }
+ // Single Session Handler //////////////////////////////////////////////////////////////////////////////
- public boolean handleRequest(LineReader r, PrintWriter pw) {
- pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
- while(true) {
+ /** takes an IMAP.Server and exposes it to the world as an IMAP server on a TCP socket */
+ public static class Listener implements Worker, Client {
+ String selectedName = null;
+ Mailbox inbox = null, root = null;
+ Server api;
+ Parser parser = null;
+ Connection conn = null;
+ public Listener() { }
+ Parser.Token token() { return parser.token(); }
+ void println(String s) { conn.println(s); }
+ void newline() { parser.newline(); }
+ Query query() { return parser.query(); }
+ public void handleRequest(Connection conn) {
+ this.conn = conn;
+ parser = new Parser(conn);
+ api = new IMAP.MailboxWrapper(new Main.BogusAuthenticator(), this);
+ conn.setTimeout(30 * 60 * 1000);
+ println("* OK " + conn.vhost + " " + IMAP.class.getName() + " IMAP4rev1 [RFC3501] v" + version + " server ready");
+ for(String tag = null;; newline()) try {
+ conn.flush();
boolean uid = false;
- String s = r.readLine();
- if (s.indexOf(' ') == -1) { pw.println("* BAD Invalid tag"); continue; }
- String tag = atom();
- String command = atom();
- if (command.equals("UID")) { uid = true; command = atom(); }
- if (command.equals("AUTHENTICATE")) { authenticate(args); }
- else if (command.equals("LIST")) list(mailbox(), mailboxPattern());
- else if (command.equals("LSUB")) lsub(mailbox(), mailboxPattern());
- else if (command.equals("CAPABILITY")) { capability(); }
- else if (command.equals("LOGIN")) login(astring(), astring());
- else if (command.equals("LOGOUT")) { logout(); conn.close(); return false; }
- else if (command.equals("RENAME")) rename(mailbox(), atom());
- else if (command.equals("APPEND")) {
- Mailbox m = mailbox();
- Token t = token();
- Token[] flags = null;
- Date arrival = null;
- if (t.type == LIST) { flags = t.l(); t = token(); }
- if (t.type == QUOTED) arrival = datetime();
- append(m, flags, arrival, literal());
- } else if (command.equals("EXAMINE")) examine(mailbox());
- else if (command.equals("COPY")) copy(set(), mailbox());
- else if (command.equals("DELETE")) delete(mailbox());
- else if (command.equals("CREATE")) create(mailbox());
- else if (command.equals("STORE")) {
- int[] messages = set();
- String what = atom();
- Token[] flags = l();
- for(int i=0; i<messages.length; i++) {
- Message m = selected.get(messages[i]);
- if (what.charAt(0) == 'F') m.deleted = m.seen = m.flagged = m.draft = m.answered = m.recent = false;
- for(int i=0; i<flags.length; i++) {
- String flag = flags[i].flag();
- if (flag.equals("Deleted")) m.deleted = what.charAt(0) != '-';
- if (flag.equals("Seen")) m.seen = what.charAt(0) != '-';
- if (flag.equals("Flagged")) m.flagged = what.charAt(0) != '-';
- if (flag.equals("Draft")) m.draft = what.charAt(0) != '-';
- if (flag.equals("Answered")) m.answered = what.charAt(0) != '-';
- if (flag.equals("Recent")) m.recent = what.charAt(0) != '-';
+ tag = null; Parser.Token tok = token(); if (tok == null) return; tag = tok.astring();
+ String command = token().atom();
+ if (command.equalsIgnoreCase("UID")) { uid = true; command = token().atom(); }
+ int commandKey = ((Integer)commands.get(command.toUpperCase())).intValue();
+ switch(commandKey) {
+ case LOGIN: api.login(token().astring(), token().astring()); 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().q()); break;
+ 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()), 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()),
+ lastfetch=token().lx(), 0, 0, 0, uid, 0); break;
+ case SEARCH: selected(); println("* SEARCH " + Printer.join(api.search(query(), uid))); 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 [UIDVALIDITY " + api.uidValidity(mailbox) + "] UIDs valid");
+ println("* OK [UIDNEXT " + api.uidNext(mailbox) + "]");
+ println("* OK [PERMANENTFLAGS (\\Seen \\Draft \\Answered \\Deleted)]");
+ selected = true;
+ break; }
+ case STATUS: {
+ String mailbox = token().astring(); // hack for GNUS buggy client
+ Parser.Token[] list = token().l();
+ String response = "";
+ for(int i=0; i<list.length; i++) {
+ String s = list[i].atom().toUpperCase();
+ if (i>0) 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);
}
- selected.add(m); // re-add
- }
- } else if (command.equals("FETCH")) {
- Set s = set();
- Token t = token();
- Token[] tl = null;
- boolean envelope = false, internaldate = false, size = false, flags = false, uid=false;
- if (t.type == Token.LIST) tl = t.l();
- else if (t.atom().equals("FULL")) { flags=true; internaldate=true; size=true; envelope=true; body=true; }
- else if (t.atom().equals("ALL")) { flags=true; internaldate=true; size=true; envelope=true; }
- else if (t.atom().equals("FAST")) { flags=true; internaldate=true; size=true; }
- else tl = new Token[] { t };
- else throw new Bad("expected atom or list");
- for (int i=0; i<tl.length; i++) {
- String s = tl[i].atom();
- if (s.equals("1")) s = "RFC822";
- else if (s.startsWith("1.")) s = s.substring(2);
- if (s.equals("ENVELOPE")) envelope = true;
- else if (s.equals("FLAGS")) flags = true;
- else if (s.equals("INTERNALDATE")) internaldate = true;
- else if (s.equals("RFC822")) body = true; // FIXME: special return syntax?
- else if (s.equals("RFC822.HEADER")) header = true;
- else if (s.equals("RFC822.SIZE")) size = true;
- else if (s.equals("RFC822.TEXT")) body = true;
- else if (s.equals("BODY")) body = true;
- else if (s.equals("BODYSTRUCTURE")) throw new No("FETCH BODYSTRUCTURE not supported");
- else if (s.equals("UID")) uid = true;
- else if (s.startsWith("BODY")) throw new No("FETCH BODY[*] not supported");
- else throw new Bad("unrecognized FETCH argument \"" + s + "\"");
+ println("* STATUS " + mailbox + " (" + response + ")");
+ break;
}
- fetch(selected, null, false, flags, internaldate, size, uid, start, end, setseen, envelope);
- } else if (command.equals("STATUS")) {
- Mailbox m = mailbox();
- Token[] attrs = l();
- boolean messages = false;
- boolean recent = false;
- boolean uidnext = false;
- boolean uidvalidity = false;
- boolean unseen = false;
- for(int i=0; i<attrs.length; i++) {
- String s = attrs[i].atom();
- if (s.equals("MESSAGES")) messages = true;
- if (s.equals("RECENT")) recent = true;
- if (s.equals("UIDNEXT")) uidnext = true;
- if (s.equals("UIDVALIDITY")) uidvalidity = true;
- if (s.equals("UNSEEN")) unseen = true;
- }
- status(mbox, messages, recent, uidnext, uidvalidity, unseen);
+ case APPEND: {
+ String m = token().astring();
+ int flags = 0;
+ 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(); }
+ api.append(m, flags, arrival, t.q());
+ break; }
+ case STORE: {
+ selected();
+ Query q = uid ? Query.uid(token().set()) : Query.num(token().set());
+ String s = token().atom().toUpperCase();
+ int flags = token().flags();
+ 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 Server.Bad("unrecognized command \"" + command + "\"");
+ }
+ println(tag+" OK "+command+" Completed. " +
+ (commandKey == LOGIN ? ("[CAPABILITY "+Printer.join(" ", api.capability())+"]") : ""));
+ } catch (Server.Bad b) { println(tag==null ? "* BAD Invalid tag":(tag + " Bad " + b.toString())); Log.warn(this,b);
+ } catch (Server.No n) { println(tag==null?"* BAD Invalid tag":(tag+" No " + n.toString())); Log.warn(this,n); }
+ }
+
+ 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 <i>or</i> 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 instanceof Query ? (Query)o : null;
+ Message m = o instanceof Message ? (Message)o : null;
+ boolean e = q == null;
+
+ 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(uid ? muid : num); r.append(" FETCH ("); }
+ int initlen = r.length();
+ if (uid) {
+ boolean good = false;
+ for(int i=0; i<t.length; i++)
+ if ((t[i].type == Parser.Token.QUOTED || t[i].type == Parser.Token.ATOM) &&
+ t[i].astring().equalsIgnoreCase("UID")) good = true;
+ if (!good) {
+ Parser.Token[] t2 = new Parser.Token[t.length + 1];
+ System.arraycopy(t, 0, t2, 0, t.length);
+ t2[t2.length - 1] = parser.token("UID");
+ lastfetch = (t = t2);
+ }
+ }
+ if (t.length == 0 && (t[0].type == Parser.Token.QUOTED || t[0].type == Parser.Token.ATOM)) {
+ if (t[0].astring().equalsIgnoreCase("ALL"))
+ t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"),
+ parser.token("ENVELOPE"), parser.token("RFC822.SIZE") };
+ else if (t[0].astring().equalsIgnoreCase("FULL"))
+ t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"), parser.token("BODY"),
+ parser.token("ENVELOPE"), parser.token("RFC822.SIZE") };
+ else if (t[0].astring().equalsIgnoreCase("FAST"))
+ t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"),
+ parser.token("RFC822.SIZE") };
+ }
+ for(int i=0; i<t.length; i++) {
+ if (r.length() > 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(m.body));}
+ } else if (s.equals("RFC822.HEADER")){ spec|=HEADER;if(e){r.append(" ");r.append(Printer.qq(m.allHeaders+"\r\n"));}
+ } else if (s.equals("RFC822.SIZE")) { spec|=RFC822SIZE; if(e){r.append(" ");r.append(m.size());}
+ } 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 {
- throw new Bad("unrecognized command \"" + command + "\"");
+ 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.allHeaders+"\r\n"+m.body; }
+ else if (s.equals("")) { spec |= RFC822TEXT; if(e) payload = m.allHeaders+"\r\n"+m.body; }
+ else if (s.equals("TEXT")) { spec |= RFC822TEXT; if(e) payload = m.body; }
+ else if (s.equals("HEADER")) { spec |= HEADER; if(e) payload = m.allHeaders+"\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<t.length - 1 && (t[i+1].s != null && t[i+1].s.startsWith("<"))) {
+ i++;
+ s = t[i].s.substring(1, t[i].s.indexOf('>'));
+ 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);
+ }
}
- }
- public static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\", "\\\\").replaceAll("\"", "\\\\\"")+"\"";}
- public static String address(Address a) { return "("+quotify(a.desciption)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
- public static String addressList(Object a) {
- if (a == null) return "NIL";
- if (a instanceof Address) return "("+address((Address)a)+")";
- Address[] aa = (Address[])a;
- StringBuffer ret = new StringBuffer();
- ret.append("(");
- for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
- ret.append(")");
- return ret.toString();
- }
-
- public static String envelope(Message m) {
- return
- "(" + quotify(m.arrival.toString()) +
- " " + quotify(m.subject) +
- " " + addressList(m.from) +
- " " + addressList(m.sender) +
- " " + addressList(m.replyTo) +
- " " + addressList(m.to) +
- " " + addressList(m.cc) +
- " " + addressList(m.bcc) +
- " " + quotify(m.headers.get("in-reply-to")) +
- " " + quotify(m.messageId) +
- ")";
- }
-
- public static void fetch(Message m, String[] headers, boolean negateHeaders, boolean flags, boolean internalDate,
- boolean size, boolean uid, int start, int end, boolean setSeen, boolean envelope) {
- String reply = "";
- if (flags)
- reply +=
- "FLAGS ("
- + m.deleted ? "\Deleted " : ""
- + m.seen ? "\Seen " : ""
- + m.flagged ? "\Flagged " : ""
- + m.draft ? "\Draft " : ""
- + m.answered ? "\Answered " : ""
- + m.recent ? "\Recent " : ""
- + ") ";
- if (size) reply += "RFC822.SIZE " m.rfc822size() + " ";;
- if (bodyStructure) // FIXME
- reply += "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " + m.rfc822size() +" "+ m.numLines() +")";
- if (envelope)
- reply +=
- "(" + quotify(m.date) +
- " " + quotify(m.subject) +
- " " + quotify(new Address[] { m.from }) + " " +
- " " + quotify(new Address[] { m.sender }) + " " +
- " " + quotify(new Address[] { m.replyTo }) + " " +
- " " + quotify(new Address[] { m.to }) + " " +
- " " + quotify(cc) + " " +
- " " + quotify(bcc) + " " +
- " " + quotify(m.headers.get("in-reply-to")) + " " +
- " " + quotify(m.messageId) +
- ") ";
- if (internaldate) reply += quotify(m.arrival) + " ";
- // FIXME
+ 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<headers.length; j++) {
+ r.append(headers[j] + (j<headers.length-1?" ":""));
+ if (m.headers.get(headers[j]) != null) payload += headers[j]+": "+m.headers.get(headers[j])+"\r\n";
+ }
+ } else {
+ throw new Server.No("HEADERS.NOT temporarily disaled");
+ /*
+ if (e) for(int j=0; j<headers.length; j++) r.append(headers[j] + (j<headers.length-1?" ":""));
+ if(e) { OUTER: for(Enumeration x=m.headers.keys(); x.hasMoreElements();) {
+ String key = (String)x.nextElement();
+ for(int j=0; j<headers.length; j++) if (key.equalsIgnoreCase(headers[j])) continue OUTER;
+ payload += key + ": " + m.headers.get(key)+"\r\n";
+ } }
+ */
+ }
+ if (e) r.append(")");
+ return payload + "\r\n";
+ }
+
+ private static final Hashtable commands = new Hashtable();
+ private static final int UID = 0; static { commands.put("UID", new Integer(UID)); }
+ private static final int AUTHENTICATE = 1; static { commands.put("AUTHENTICATE", new Integer(AUTHENTICATE)); }
+ private static final int LIST = 2; static { commands.put("LIST", new Integer(LIST)); }
+ private static final int LSUB = 3; static { commands.put("LSUB", new Integer(LSUB)); }
+ private static final int SUBSCRIBE = 4; static { commands.put("SUBSCRIBE", new Integer(SUBSCRIBE)); }
+ private static final int UNSUBSCRIBE = 5; static { commands.put("UNSUBSCRIBE", new Integer(UNSUBSCRIBE)); }
+ private static final int CAPABILITY = 6; static { commands.put("CAPABILITY", new Integer(CAPABILITY)); }
+ private static final int ID = 7; static { commands.put("ID", new Integer(ID)); }
+ private static final int LOGIN = 8; static { commands.put("LOGIN", new Integer(LOGIN)); }
+ private static final int LOGOUT = 9; static { commands.put("LOGOUT", new Integer(LOGOUT)); }
+ private static final int RENAME = 10; static { commands.put("RENAME", new Integer(RENAME)); }
+ private static final int EXAMINE = 11; static { commands.put("EXAMINE", new Integer(EXAMINE)); }
+ private static final int SELECT = 12; static { commands.put("SELECT", new Integer(SELECT)); }
+ private static final int COPY = 13; static { commands.put("COPY", new Integer(COPY)); }
+ private static final int DELETE = 14; static { commands.put("DELETE", new Integer(DELETE)); }
+ private static final int CHECK = 15; static { commands.put("CHECK", new Integer(CHECK)); }
+ private static final int NOOP = 16; static { commands.put("NOOP", new Integer(NOOP)); }
+ private static final int CLOSE = 17; static { commands.put("CLOSE", new Integer(CLOSE)); }
+ private static final int EXPUNGE = 18; static { commands.put("EXPUNGE", new Integer(EXPUNGE)); }
+ private static final int UNSELECT = 19; static { commands.put("UNSELECT", new Integer(UNSELECT)); }
+ private static final int CREATE = 20; static { commands.put("CREATE", new Integer(CREATE)); }
+ private static final int STATUS = 21; static { commands.put("STATUS", new Integer(STATUS)); }
+ private static final int FETCH = 22; static { commands.put("FETCH", new Integer(FETCH)); }
+ private static final int APPEND = 23; static { commands.put("APPEND", new Integer(APPEND)); }
+ private static final int STORE = 24; static { commands.put("STORE", new Integer(STORE)); }
+ private static final int SEARCH = 25; static { commands.put("SEARCH", new Integer(SEARCH)); }
}
- public static Query parseQuery() {
- String tok = null;
- boolean not = false;
- while(true) {
- Token t = token();
- if (t.type == t.LIST) { }
- else if (t.type == t.SET) { }
- tok = t.atom();
- if (tok.equals("NOT")) { not = true; continue; }
- if (tok.equals("OR")) { /* FIXME */ }
- if (tok.equals("AND")) { /* FIXME */ }
- break;
+ public static class Parser {
+ private Stream stream;
+ public Parser(Stream from) { this.stream = from; }
+ public Token token(String s) { return new Token(s); }
+ protected Query query() {
+ String s = null;
+ boolean not = false;
+ Query q = null;
+ while(true) {
+ Parser.Token t = token(false);
+ if (t == null) break;
+ if (t.type == t.LIST) throw new Server.No("nested queries not yet supported FIXME");
+ else if (t.type == t.SET) return Query.num(t.set());
+ s = t.atom().toUpperCase();
+ if (s.equals("NOT")) { not = true; continue; }
+ if (s.equals("OR")) return Query.or(query(), query()); // FIXME parse rest of list
+ if (s.equals("AND")) return Query.and(query(), query());
+ }
+ if (s.startsWith("UN")) { not = true; s = s.substring(2); }
+ if (s.equals("ANSWERED")) q = Query.answered();
+ else if (s.equals("DELETED")) q = Query.deleted();
+ else if (s.equals("ALL")) q = Query.all();
+ else if (s.equals("DRAFT")) q = Query.draft();
+ else if (s.equals("FLAGGED")) q = Query.flagged();
+ else if (s.equals("RECENT")) q = Query.recent();
+ else if (s.equals("SEEN")) q = Query.seen();
+ else if (s.equals("OLD")) { not = true; q = Query.recent(); }
+ else if (s.equals("NEW")) q = Query.and(Query.recent(), Query.not(Query.seen()));
+ else if (s.equals("KEYWORD")) q = Query.header("keyword", token().flag());
+ else if (s.equals("HEADER")) q = Query.header(token().astring(), token().astring());
+ else if (s.equals("BCC")) q = Query.header("bcc", token().astring());
+ else if (s.equals("CC")) q = Query.header("cc", token().astring());
+ else if (s.equals("FROM")) q = Query.header("from", token().astring());
+ else if (s.equals("TO")) q = Query.header("to", token().astring());
+ else if (s.equals("SUBJECT")) q = Query.header("subject", token().astring());
+ else if (s.equals("LARGER")) q = Query.size(token().n(), Integer.MAX_VALUE);
+ else if (s.equals("SMALLER")) q = Query.size(Integer.MIN_VALUE, token().n());
+ else if (s.equals("BODY")) q = Query.body(token().astring());
+ else if (s.equals("TEXT")) q = Query.full(token().astring());
+ else if (s.equals("BEFORE")) q = Query.arrival(new Date(0), token().date());
+ else if (s.equals("SINCE")) q = Query.arrival(token().date(), new Date(Long.MAX_VALUE));
+ else if (s.equals("ON")) { Date d = token().date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
+ else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), token().date());
+ else if (s.equals("SENTSINCE")) q = Query.sent(token().date(), new Date(Long.MAX_VALUE));
+ else if (s.equals("SENTON")) { Date d = token().date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
+ else if (s.equals("UID")) q = Query.uid(token().set());
+ return q;
}
- if (tok.startsWith("UN")) { not = true; tok = tok.substring(2); }
- if (tok.equals("ANSWERED")) q = new Query.Flag(Query.Flag.ANSWERED);
- else if (tok.equals("DELETED")) q = new Query.Flag(Query.Flag.ANSWERED);
- else if (tok.equals("DRAFT")) q = new Query.Flag(Query.Flag.ANSWERED);
- else if (tok.equals("FLAGGED")) q = new Query.Flag(Query.Flag.ANSWERED);
- else if (tok.equals("RECENT")) q = new Query.Flag(Query.Flag.ANSWERED);
- else if (tok.equals("SEEN")) q = new Query.Flag(Query.Flag.ANSWERED);
- else if (tok.equals("OLD")) { not = true; q = new Query.Flag(Query.Flag.RECENT); }
- else if (tok.equals("NEW")) q = new Query.And(new Query.Flag(Query.Flag.RECENT),
- new Query.Not(new Query.Flag(Query.Flag.SEEN)));
- else if (tok.equals("KEYWORD")) q = new Query.Header("keyword", flag());
- else if (tok.equals("HEADER")) q = new Query.Header(astring(), astring());
- else if (tok.equals("BCC")) q = new Query.Header("bcc", astring());
- else if (tok.equals("CC")) q = new Query.Header("cc", astring());
- else if (tok.equals("FROM")) q = new Query.Header("from", astring());
- else if (tok.equals("TO")) q = new Query.Header("to", astring());
- else if (tok.equals("SUBJECT")) q = new Query.Header("subject", astring());
- else if (tok.equals("BEFORE")) q = new Query.Arrival(date(), true, false);
- else if (tok.equals("SINCE")) q = new Query.Arrival(date(), false, true);
- else if (tok.equals("ON")) q = new Query.Arrival(date(), true, true);
- else if (tok.equals("LARGER")) q = new Query.Size(n(), true);
- else if (tok.equals("SMALLER")) q = new Query.Size(n(), false);
- else if (tok.equals("BODY")) q = new Query.FullText(astring(), true, false);
- else if (tok.equals("TEXT")) q = new Query.FullText(astring(), true, true);
- else if (tok.equals("SENTBEFORE")) { /* FIXME date() */ }
- else if (tok.equals("SENTSINCE")) { /* FIXME date() */ }
- else if (tok.equals("SENTON")) { /* FIXME date() */ }
- else if (tok.equals("UID")) { /* FIXME set() */ }
- }
- private static class Token {
- private byte type;
- private final String s;
- private final Token[] l;
- private final int n;
- private static final byte NIL = 0;
- private static final byte LIST = 1;
- private static final byte QUOTED = 2;
- private static final byte NUMBER = 3;
- public Token() { n = 0; list = null; s = null; type = NIL; }
- public Token(String quoted) { s = quoted; l = null; type = QUOTED; n = 0; }
- public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
- public Token(int number) { n = number; list = null; s = null; type = NUMBER; }
-
- // assumes token is a flag list or a fag
- public void setFlags(Message m) { }
- public void addFlags(Message m) { }
- public void deleteFlags(Message m) { }
-
- public String mailboxPattern() {
- /* 1*(ATOM_CHAR / "%" / "*") / string */
+ private static void bad(String s) { throw new Server.Bad(s); }
+ class Token {
+ public final byte type;
+ private final String s;
+ private final Parser.Token[] l;
+ private final int n;
+ private static final byte NIL = 0, LIST = 1, QUOTED = 2, NUMBER = 3, ATOM = 4, BAREWORD = 5, SET = 6;
+ public Token() { this.s = null; n = 0; l = null; type = NIL; }
+ public Token(String s) { this(s, false); }
+ public Token(String s, boolean quoted) { this.s = s; n = 0; l = null; type = quoted ? QUOTED : ATOM; }
+ public Token(Parser.Token[] list) { this.s = null; n = 0; l = list; type = LIST; }
+ public Token(int number) { this.s = null; n = number; l = null; type = NUMBER; }
+
+ public String flag() { if (type != ATOM) bad("expected a flag"); return s; }
+ public int n() { if (type != NUMBER) bad("expected number"); return n; }
+ public int nz() { int n = n(); if (n == 0) bad("expected nonzero number"); return n; }
+ public String q() { if (type == NIL) return null; if (type != QUOTED) bad("expected qstring"); return s; }
+ public Parser.Token[] l() { if (type == NIL) return null; if (type != LIST) bad("expected list"); return l; }
+ public Parser.Token[] lx() {
+ if (type == LIST) return l;
+ Vec v = new Vec();
+ v.addElement(this);
+ while(true) {
+ Parser.Token t = token(false);
+ if (t == null) break;
+ v.addElement(t);
+ }
+ Parser.Token[] ret = new Parser.Token[v.size()];
+ v.copyInto(ret);
+ return ret;
+ }
+ public String nstring() { if (type==NIL) return null; if (type!=QUOTED) bad("expected nstring"); return s; }
+ public String astring() {
+ if (type != ATOM && type != QUOTED) bad("expected atom or string");
+ if (s == null) bad("astring cannot be null");
+ return s; }
+ public String[] sl() {
+ if (type == NIL) return null;
+ if (type != LIST) bad("expected list");
+ String[] ret = new String[l.length];
+ for(int i=0; i<ret.length; i++) ret[i] = l[i].s;
+ return ret;
+ }
+ public int flags() {
+ if (type != LIST) bad("expected flag list");
+ int ret = 0;
+ for(int i=0; i<l.length; i++) {
+ String flag = l[i].s;
+ if (flag.equals("\\Deleted")) ret |= Mailbox.Flag.DELETED;
+ else if (flag.equals("\\Seen")) ret |= Mailbox.Flag.SEEN;
+ else if (flag.equals("\\Flagged")) ret |= Mailbox.Flag.FLAGGED;
+ else if (flag.equals("\\Draft")) ret |= Mailbox.Flag.DRAFT;
+ else if (flag.equals("\\Answered")) ret |= Mailbox.Flag.ANSWERED;
+ else if (flag.equals("\\Recent")) ret |= Mailbox.Flag.RECENT;
+ }
+ return ret;
+ }
+ public int[] set() {
+ if (type != ATOM) bad("expected a messageid set");
+ Vec.Int ids = new Vec.Int();
+ StringTokenizer st = new StringTokenizer(s, ",");
+ while(st.hasMoreTokens()) {
+ String s = st.nextToken();
+ if (s.indexOf(':') == -1) {
+ if (s.equals("*")) {
+ ids.addElement(0);
+ ids.addElement(Integer.MAX_VALUE);
+ } else {
+ ids.addElement(Integer.parseInt(s));
+ ids.addElement(Integer.parseInt(s));
+ }
+ continue; }
+ int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
+ String end_s = s.substring(s.indexOf(':')+1);
+ if (end_s.equals("*")) { ids.addElement(start); ids.addElement(Integer.MAX_VALUE); }
+ else {
+ int end = Integer.parseInt(end_s);
+ for(int j=Math.min(start,end); j<=Math.max(start,end); j++) {
+ ids.addElement(j);
+ ids.addElement(j);
+ }
+ }
+ }
+ return ids.dump();
+ }
+ public Date date() {
+ if (type != QUOTED && type != ATOM) bad("Expected quoted or unquoted date");
+ try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
+ } catch (ParseException p) { throw new Server.Bad("invalid date format; " + p); }
+ }
+ public Date datetime() {
+ if (type != QUOTED) bad("Expected quoted datetime");
+ try { return new SimpleDateFormat("dd-MM-yyyy hh:mm:ss zzzz").parse(s.trim());
+ } catch (ParseException p) { throw new Server.Bad("invalid datetime format " + s + " : " + p); }
+ }
+ public String atom() {
+ if (type != ATOM) bad("expected atom");
+ for(int i=0; i<s.length(); i++) {
+ char c = s.charAt(i);
+ if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*' || c == '\"' | c == '\\')
+ bad("invalid char in atom: " + c);
+ }
+ return s;
+ }
}
- public String flag() throws Bad {
- if (type != ATOM) throw new Bad("expected a flag");
- return s; // if first char != backslash, it is a keyword-flag
+
+ public void newline() {
+ while (stream.peekc() == '\r' || stream.peekc() == '\n' || stream.peekc() == ' ') {
+ for(char c = stream.peekc(); c == ' ';) { stream.getc(); c = stream.peekc(); };
+ for(char c = stream.peekc(); c == '\r' || c == '\n';) { stream.getc(); c = stream.peekc(); };
+ }
}
- public int n() throws Bad {
- if (type != NUMBER) throw new Bad("expected number");
- return n;
+
+ public Token token() { return token(true); }
+ public Token token(boolean freak) {
+ Vec toks = new Vec();
+ StringBuffer sb = new StringBuffer();
+ char c = stream.getc(); while (c == ' ') c = stream.getc();
+ if (c == '\r' || c == '\n') { if (freak) bad("unexpected end of line"); return null; }
+ else if (c == '{') {
+ while(stream.peekc() != '}') sb.append(stream.getc());
+ stream.getc();
+ stream.println("+ Ready when you are...");
+ int octets = Integer.parseInt(sb.toString());
+ while(stream.peekc() == ' ') stream.getc(); // whitespace
+ while(stream.peekc() == '\n' || stream.peekc() == '\r') stream.getc();
+ byte[] bytes = new byte[octets];
+ int numread = 0;
+ while(numread < bytes.length) {
+ int n = stream.read(bytes, numread, bytes.length - numread);
+ if (n == -1) bad("end of stream while reading IMAP qstring");
+ numread += n;
+ }
+ return new Token(new String(bytes), true);
+ } else if (c == '\"') {
+ while(true) {
+ c = stream.getc();
+ if (c == '\\') sb.append(stream.getc());
+ else if (c == '\"') break;
+ else sb.append(c);
+ }
+ return new Token(sb.toString(), true);
+
+ // NOTE: this is technically a violation of the IMAP grammar, since atoms like FOO[BAR should be legal
+ } else if (c == ']' || c == ')') { return null;
+ } else if (c == '[' || c == '(') {
+ Token t;
+ do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
+ Token[] ret = new Token[toks.size()];
+ toks.copyInto(ret);
+ return new Token(ret);
+
+ } else while(true) {
+ sb.append(c);
+ c = stream.peekc();
+ if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '[' || c == ']' ||
+ c == '{' || c == '\n' || c == '\r')
+ return new Token(sb.toString(), false);
+ stream.getc();
+ }
}
- public int nz() throws Bad {
- if (type != NUMBER) throw new Bad("expected number");
- if (n == 0) throw new Bad("expected nonzero number");
- return n;
+ }
+
+ public static class Printer {
+ static String quotify(String s){
+ return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
+ static String quotify(Date d) {
+ return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
+ static String address(Address a) {
+ return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
+ public static String addressList(Object a) {
+ if (a == null) return "NIL";
+ if (a instanceof Address) return "("+address((Address)a)+")";
+ Address[] aa = (Address[])a;
+ StringBuffer ret = new StringBuffer();
+ ret.append("(");
+ for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
+ ret.append(")");
+ return ret.toString();
+ }
+ static String flags(Mailbox.Iterator it) {
+ return
+ (it.deleted() ? "\\Deleted " : "") +
+ (it.seen() ? "\\Seen " : "") +
+ (it.flagged() ? "\\Flagged " : "") +
+ (it.draft() ? "\\Draft " : "") +
+ (it.answered() ? "\\Answered " : "") +
+ (it.recent() ? "\\Recent " : "");
}
- public String q() throws Bad {
- if (type == NIL) return null;
- if (type != QUOTED) throw new Bad("expected qstring");
- return s;
+ static String flags(int flags) {
+ String ret = "(" +
+ (((flags & Mailbox.Flag.DELETED) == Mailbox.Flag.DELETED) ? "\\Deleted " : "") +
+ (((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) ? "\\Seen " : "") +
+ (((flags & Mailbox.Flag.FLAGGED) == Mailbox.Flag.FLAGGED) ? "\\Flagged " : "") +
+ (((flags & Mailbox.Flag.DRAFT) == Mailbox.Flag.DRAFT) ? "\\Draft " : "") +
+ (((flags & Mailbox.Flag.ANSWERED) == Mailbox.Flag.ANSWERED)? "\\Answered " : "") +
+ (((flags & Mailbox.Flag.RECENT) == Mailbox.Flag.RECENT) ? "\\Recent " : "");
+ if (ret.endsWith(" ")) ret = ret.substring(0, ret.length() - 1);
+ return ret + ")";
}
- public String nstring() throws Bad {
+ static String bodystructure(Message m) {
+ // FIXME
+ return "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"ISO-8859-1\") NIL NIL \"7BIT\" "+m.size()+" "+m.lines+")";
}
- public Token[] l() throws Bad {
- if (type == NIL) return null;
- if (type != LIST) throw new Bad("expected parenthesized list");
- return l;
+ static String message(Message m) { return m.toString(); }
+ static String date(Date d) { return d.toString(); }
+ static String envelope(Message m) {
+ return
+ "(" + quotify(m.arrival.toString()) +
+ " " + quotify(m.subject) +
+ " " + addressList(m.from) +
+ " " + addressList(m.headers.get("sender")) +
+ " " + addressList(m.replyto) +
+ " " + addressList(m.to) +
+ " " + addressList(m.cc) +
+ " " + addressList(m.bcc) +
+ " " + quotify((String)m.headers.get("in-reply-to")) +
+ " " + quotify(m.messageid) +
+ ")";
}
- public int[] set() throws Bad {
- // FIXME <set>,<set> <n> <n>:<n> * (* = largest)
+
+ public static String qq(String s) {
+ StringBuffer ret = new StringBuffer();
+ ret.append('{');
+ ret.append(s.length());
+ ret.append('}');
+ ret.append('\r');
+ ret.append('\n');
+ ret.append(s);
+ return ret.toString();
}
- public Date date() throws Bad {
- // may be quoted or unquoted
- try {
- new SimpleDateFormat("dd-MMM-yyyy").parse(s);
- } catch (DateParsingException) {
+
+ private static String join(int[] nums) {
+ StringBuffer ret = new StringBuffer();
+ for(int i=0; i<nums.length; i++) {
+ ret.append(nums[i]);
+ if (i<nums.length-1) ret.append(' ');
}
+ return ret.toString();
}
- public String nstring() throws Bad {
- if (type == NIL) return null;
- if (type == QUOTED) return s;
- throw new Bad("expected NIL or string");
- }
- public String astring() throws Bad {
- if (type == ATOM) return s;
- if (type == QUOTED) return s;
- throw new Bad("expected atom or string");
- }
- public String atom() throws Bad {
- // ATOM_CHAR ::= <any CHAR except atom_specials>
- // atom_specials ::= "(" / ")" / "{" / SPACE / CTL / list_wildcards / quoted_specials
- if (type != ATOM) throw new Bad("expected atom");
- }
- public Mailbox mailbox() throws Bad {
- if (type == BAREWORD && s.toLowerCase().equals("inbox")) return Mailbox.INBOX;
- return Mailbox.getMailbox(astring());
+ private static String join(String delimit, String[] stuff) {
+ StringBuffer ret = new StringBuffer();
+ for(int i=0; i<stuff.length; i++) {
+ ret.append(stuff[i]);
+ if (i<stuff.length - 1) ret.append(delimit);
+ }
+ return ret.toString();
}
- public Date datetime() throws Bad {
- // expected to be a quoted string
-
- new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").parse(s);
}
- }
-
-
- // literal ::= "{" number "}" CRLF *CHAR8 ;; Number represents the number of CHAR8 octets
+ // Main //////////////////////////////////////////////////////////////////////////////
- public static Token[] tokenize(String s) {
- Vec toks = new Vec();
- StringBuffer sb = new StringBuffer();
- for(int i=0; i<s.length();) {
- sb.setSize(0);
- if (s.charAt(i) == '\"') {
- for(i++; i < s.length(); i++) {
- if (s.charAt(i) == '\\') sb.append(s.charAt(++i));
- else if (s.charAt(i) == '\"') { i++; break; }
- else sb.append(s.charAt(i));
- }
- } else if (s.charAt(i) == '(') {
- // FIXME, deal with strings within parens
- } else {
- for(; i < s.length(); i++)
- if (s.charAt(i) == ' ' || s.charAt(i) == '\"') break;
- else sb.append(s.charAt(i));
- }
- toks.addElement(sb.toString());
- while (i < s.length() && s.charAt(i) == ' ') i++;
+ /** simple listener for testing purposes */
+ public static void main(String[] args) throws Exception {
+ ServerSocket ss = new ServerSocket(143);
+ for(;;) {
+ final Socket s = ss.accept();
+ new Thread() { public void run() { try {
+ final Mailbox root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT+File.separatorChar+"imap", true);
+ new Listener();
+ } catch (Exception e) { e.printStackTrace(); } } }.start();
}
- return toks.toArray();
}
+
+ public static final int
+ PEEK=0x1, BODYSTRUCTURE=0x2, ENVELOPE=0x4, FLAGS=0x8, INTERNALDATE=0x10, FIELDS=0x800, FIELDSNOT=0x1000,
+ RFC822=0x20, RFC822TEXT=0x40, RFC822SIZE=0x80, HEADERNOT=0x100, UID=0x200, HEADER=0x400;
}