X-Git-Url: http://git.megacz.com/?a=blobdiff_plain;f=src%2Forg%2Fibex%2Fmail%2Fprotocol%2FIMAP.java;h=f6c084fb0fbae64640346b0d551e9cdd5ed2d115;hb=d10aa46b70cf0b6aa92b6a763b276fdb9ec1bc6b;hp=0db26a2b6d94fdb30a8318a1a6d7f0911dd087a0;hpb=bec53dd0b091f3e94643fb9918e8d68c9fff98a5;p=org.ibex.mail.git diff --git a/src/org/ibex/mail/protocol/IMAP.java b/src/org/ibex/mail/protocol/IMAP.java index 0db26a2..f6c084f 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,522 +13,844 @@ 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: hoist all the ok()'s? +// 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 { - - 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 { - new Listener(s, "megacz.com").handleRequest(); - } catch (Exception e) { - e.printStackTrace(); - } - } - }.start(); - } +// FEATURE: \Noselect +// FEATURE: subscriptions +// FEATURE: tune for efficiency +// FEATURE: STARTTLS +// FEATURE: asynchronous client notifications (need to re-read RFC) + +public class IMAP { + + 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.getBody().getStream().transcribe(sb); + return sb.toString(); } - public static class Exn extends MailException { - public Exn(String s) { super(s); } - public static class No extends Exn { public No(String s) { super(s); } } + // 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 + } + + 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); } } } - private static class Listener extends Incoming { + + // 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; Mailbox root = null; + Mailbox selected() { if (selected == null) throw new Bad("no mailbox selected"); return selected; } + final Login auth; + final Client client; - Socket conn; - String vhost; - PrintWriter pw; - InputStream is; - PushbackReader r; - public void init() { } - public Listener(Socket conn, String vhost) throws IOException { - this.vhost = vhost; - this.conn = conn; - this.selected = null; - this.pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream())); - this.is = conn.getInputStream(); - this.r = new PushbackReader(new InputStreamReader(is)); - } - - // ugly: not concurrent - String tag; - private void ok(String s) { pw.println(tag + " OK " + s); } - private void star(String s) { pw.println("* " + s); } + public MailboxWrapper(Login auth, Client c) { this.auth=auth; this.client=c;} + public void setClient(IMAP.Client client) { } - // FIXME should throw a No if mailbox not found and create==false - 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; - while(name.length() > 0) { - int end = name.length(); - if (name.indexOf('.') != -1) end = name.indexOf('.'); - m = m.slash(name.substring(0, end), create); - name = name.substring(end); - } + 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; } - public void lsub(Mailbox m, String s) { star("LIST () \".\" INBOX"); ok("LSUB completed"); } // FIXME - public void list(Mailbox m, String s) { star("LIST () \".\" INBOX"); ok("LIST completed"); } // FIXME - - private boolean auth(String user, String pass) { /* FEATURE */ return user.equals("megacz") && pass.equals(""); } - public void copy(int[] set, Mailbox target) { for(int i=0; i 0 ? sep+"" : "") + s; + if (mailbox(kid, false) == null) continue; + Mailbox phant = mailbox(kid, false, false); + if (phant != null) { + boolean phantom = phant.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; + } + } } - star("STATUS " + m.getName() + " (" + response + ")"); } - public void select(String mailbox, boolean examineOnly) { - selected = getMailbox(mailbox, false); - star(selected.list().length + " EXISTS"); - int recent = 0; - int[] list = selected.list(); for(int i=0; i')); - s = s.substring(0, s.indexOf('<')); - if (range.indexOf('.') == -1) end = Integer.MAX_VALUE; - else { - end = Integer.parseInt(range.substring(range.indexOf('.') + 1)); - range = range.substring(0, range.indexOf('.')); + private int maxn(boolean uid) { return uid ? api.maxuid() : api.count(); } + + 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;;) try { + conn.flush(); + boolean uid = false; + 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: 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().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().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); } - start = Integer.parseInt(range); + println("* STATUS " + mailbox + " (" + response + ")"); + break; } - if (s.equals("ENVELOPE") || all || full) reply.append("ENVELOPE " + envelope(m) + " "); - if (s.equals("FLAGS") || full || all || fast) reply.append("FLAGS (" + flags(selected, set[j]) + ") "); - if (s.equals("INTERNALDATE") || full || all || fast) reply.append("INTERNALDATE "+quotify(m.arrival)+" "); - if (s.equals("RFC822.SIZE") || full || all || fast) reply.append("RFC822.SIZE " + m.rfc822size() + " "); - if (s.equals("RFC822.HEADER") || s.equals("BODY[HEADER]")) - { reply.append("BODY[HEADER] {" + m.allHeaders.length() + "}\r\n"); reply.append(m.allHeaders); } - if (s.equals("RFC822")||s.equals("RFC822.TEXT")||s.equals("BODY")||s.equals("BODY[]")||s.equals("TEXT")||full) - { reply.append("BODY[TEXT] {" + m.body.length() + "}\r\n"); reply.append(m.body); } - if (s.equals("UID")) reply.append("UID " + selected.uid(set[j])); - if (s.equals("MIME")) throw new Exn.No("FETCH BODY.MIME not supported"); - if (s.startsWith("BODY[HEADER.FIELDS")) throw new Exn.No("partial headers not supported"); - if (s.startsWith("BODY[HEADER.FIELDS.NOT")) throw new Exn.No("partial headers not supported"); - if (s.equals("BODYSTRUCTURE")) - reply.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " + - m.rfc822size()+" "+ m.lines +")"); + 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(maxn(uid))) : Query.num(token().set(maxn(uid))); + 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 + "\""); } - star(set[j] + " FETCH (" + reply.toString() + ")"); - // FEATURE set seen flag if not BODY.PEEK - } + println(tag+" OK "+command+" Completed. " + + (commandKey == LOGIN ? ("[CAPABILITY "+Printer.join(" ", api.capability())+"]") : "")); + try { + newline(); + } catch (Stream.EOF e) { + Log.info(this, "connection closed"); + return; + } + } 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); } } - public void store(int[] messages, String what, Token[] flags) { - for(int i=0; ior 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)); } } - selected.add(m); // re-add } + if (e) { + r.append(")"); + println("* " + r.toString()); + } else { + api.fetch(q, spec, headers, start, end, uid); + } } - public boolean handleRequest() throws IOException { - LineReader lr = new LineReader(r); - pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready"); - while(true) { - boolean uid = false; - String s = lr.readLine(); - if (s.indexOf(' ') == -1) { pw.println("* BAD Invalid tag"); continue; } - tag = atom(); - String command = atom(); - if (command.equals("UID")) { uid = true; command = atom(); } - if (command.equals("AUTHENTICATE")) { login(astring(), astring()); } - 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")) append(mailbox(), token()); - else if (command.equals("EXAMINE")) select(astring(), true); - else if (command.equals("SELECT")) select(astring(), false); - else if (command.equals("COPY")) copy(set(), mailbox()); - else if (command.equals("DELETE")) delete(mailbox()); - else if (command.equals("CHECK")) check(); - else if (command.equals("CREATE")) create(astring()); - else if (command.equals("STORE")) store(set(), atom(), l()); - else if (command.equals("FETCH")) fetch(set(), token()); - else if (command.equals("STATUS")) status(mailbox(), l()); - else throw new Exn.Bad("unrecognized command \"" + command + "\""); + 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