1 package org.ibex.mail.protocol;
2 import org.ibex.mail.*;
3 import org.ibex.util.*;
4 import org.ibex.mail.target.*;
10 // FEATURE: hoist all the ok()'s?
11 // FEATURE: pipelining
12 // FEATURE: support [charset]
13 public class IMAP extends MessageProtocol {
15 public static final char imapSeparator = '.';
17 public static void main(String[] args) throws Exception {
18 ServerSocket ss = new ServerSocket(143);
20 System.out.println("listening");
21 final Socket s = ss.accept();
22 System.out.println("connected");
27 FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT + File.separatorChar + "imap", true);
28 Mailbox inbox = root.slash("users", true).slash("megacz", true);
29 new Listener(s, "megacz.com", root, inbox).handleRequest();
30 } catch (Exception e) {
38 public static class Exn extends MailException {
39 public Exn(String s) { super(s); }
40 public static class No extends Exn { public No(String s) { super(s); } }
41 public static class Bad extends Exn { public Bad(String s) { super(s); } }
44 private static class Listener extends Incoming {
45 Mailbox selected = null;
53 public void init() { }
54 public Listener(Socket conn, String vhost, Mailbox root, Mailbox inbox) throws IOException {
60 this.pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
61 this.is = conn.getInputStream();
62 this.r = new PushbackReader(new InputStreamReader(is));
65 private void star(String s) { pw.println("* " + s); }
67 // FIXME should throw a No if mailbox not found and create==false
68 private Mailbox getMailbox(String name, boolean create) {
70 while(name.length() > 0) {
71 int end = name.length();
72 if (name.indexOf(imapSeparator) != -1) end = name.indexOf(imapSeparator);
73 m = m.slash(name.substring(0, end), create);
74 name = name.substring(end);
79 private boolean auth(String user, String pass) { /* FEATURE */ return user.equals("megacz") && pass.equals(""); }
81 public void lsub(Mailbox m, String s) { star("LIST () \".\" INBOX"); } // FEATURE
82 public void list(Mailbox m, String s) { star("LIST () \".\" INBOX"); } // FEATURE
83 public void copy(final Query q, Mailbox to) { for(Mailbox.Iterator it=selected.iterator(q);it.next();) to.add(it.cur()); }
84 public void login(String user, String pass) { if (!auth(user, pass)) throw new Exn.No("Liar, liar, pants on fire."); }
85 public void capability() { star("CAPABILITY IMAP4rev1"); }
86 public void logout() { star("BYE LOGOUT received"); }
87 public void delete(Mailbox m) { if (!m.equals(inbox)) m.destroy(); }
88 public void create(String mailbox){if(!mailbox.endsWith(".")&&!mailbox.equalsIgnoreCase("inbox"))getMailbox(mailbox,true);}
89 public void close(boolean examineOnly) { expunge(false, true); selected = null; }
90 public void check() { }
92 public void rename(Mailbox from, String to) {
93 if (from.equals(inbox)) from.copy(Query.all(), getMailbox(to, true));
94 else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), getMailbox(to, true)); from.destroy(); }
98 public void status(final Mailbox m, Token[] attrs) {
99 int count0 = 0, count1 = 0, count2 = 0;
100 for(Mailbox.Iterator it = m.iterator(); it.next(); ) { if (!it.seen()) count0++; if (it.recent()) count1++; count2++; }
101 String response = "";
102 for(int i=0; i<attrs.length; i++) {
103 String s = attrs[i].atom();
104 if (s.equals("MESSAGES")) response += "MESSAGES " + count2;
105 if (s.equals("RECENT")) response += "RECENT " + count0;
106 if (s.equals("UIDNEXT")) response += "UNSEEN " + count1;
107 if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + m.uidValidity();
108 if (s.equals("UNSEEN")) response += "UIDNEXT " + m.uidNext();
110 star("STATUS " + /* FIXME m.getName() +*/ " (" + response + ")");
113 public void select(String mailbox, boolean examineOnly) {
114 selected = getMailbox(mailbox, false);
115 star(selected.count(Query.all()) + " EXISTS");
116 star(selected.count(Query.recent()) + " RECENT");
117 //star("OK [UNSEEN 12] Message 12 is first unseen"); FEATURE
118 star("OK [UIDVALIDITY " + selected.uidValidity() + "] UIDs valid");
119 star("FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
120 // FEATURE: READ-WRITE / READ-ONLY
123 public void expunge(final boolean examineOnly, final boolean silent) {
124 if (selected == null) throw new Exn.Bad("no mailbox selected");
125 for(Mailbox.Iterator it = selected.iterator(); it.next();) {
126 if (!it.deleted()) return;
127 if (!silent) star(it.uid() + " EXPUNGE");
128 if (!examineOnly) it.delete();
132 public void append(Mailbox m, Token t) {
133 Token[] flags = null;
135 if (t.type == t.LIST) { flags = t.l(); t = token(); }
136 if (t.type == t.QUOTED) { arrival = t.datetime(); t = token(); }
137 String literal = q();
138 selected.add(new Message(null, null, new LineReader(new StringReader(literal))));
139 if (flags != null) { /* FEATURE */ }
142 public void fetch(Query q, Token t) {
144 int start = -1, end = -1;
145 boolean peek = false, fast = false, all = false, full = false;
146 if (t.type == Token.LIST) tl = t.l();
147 else if (t.atom().equals("FULL")) full = true;
148 else if (t.atom().equals("ALL")) all = true;
149 else if (t.atom().equals("FAST")) fast = true;
150 StringBuffer reply = new StringBuffer();
151 for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
152 Message m = it.cur();
153 for (int i=0; i<tl.length; i++) {
154 String s = tl[i].atom();
155 if (s.startsWith("BODY.PEEK")) { peek = true; s = "BODY" + s.substring(9); }
156 if (s.startsWith("BODY.1")) s = "BODY" + s.substring(6);
157 if (s.indexOf('<') != -1) {
158 String range = s.substring(s.indexOf('<') + 1, s.indexOf('>'));
159 s = s.substring(0, s.indexOf('<'));
160 if (range.indexOf(imapSeparator) == -1) end = Integer.MAX_VALUE;
162 end = Integer.parseInt(range.substring(range.indexOf(imapSeparator) + 1));
163 range = range.substring(0, range.indexOf(imapSeparator));
165 start = Integer.parseInt(range);
167 if (s.equals("ENVELOPE") || all || full) reply.append("ENVELOPE " + envelope(m) + " ");
168 if (s.equals("FLAGS") || full || all || fast) reply.append("FLAGS (" + flags(it) + ") ");
169 if (s.equals("INTERNALDATE") || full || all || fast) reply.append("INTERNALDATE "+quotify(m.arrival)+" ");
170 if (s.equals("RFC822.SIZE") || full || all || fast) reply.append("RFC822.SIZE " + m.rfc822size() + " ");
171 if (s.equals("RFC822.HEADER") || s.equals("BODY[HEADER]"))
172 { reply.append("BODY[HEADER] {" + m.allHeaders.length() + "}\r\n"); reply.append(m.allHeaders); }
173 if (s.equals("RFC822")||s.equals("RFC822.TEXT")||s.equals("BODY")||s.equals("BODY[]")||s.equals("TEXT")||full)
174 { reply.append("BODY[TEXT] {" + m.body.length() + "}\r\n"); reply.append(m.body); }
175 if (s.equals("UID")) reply.append("UID " + it.uid());
176 if (s.equals("MIME")) throw new Exn.No("FETCH BODY.MIME not supported");
177 if (s.startsWith("BODY[HEADER.FIELDS")) throw new Exn.No("partial headers not supported");
178 if (s.startsWith("BODY[HEADER.FIELDS.NOT")) throw new Exn.No("partial headers not supported");
179 if (s.equals("BODYSTRUCTURE"))
180 reply.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " +
181 m.rfc822size()+" "+ m.lines +")");
183 star(it.num() + " FETCH (" + reply.toString() + ")");
184 // FEATURE: range requests
185 // FEATURE set seen flag if not BODY.PEEK
189 // FEATURE: hoist the parsing here
190 public void store(Query q, String what, Token[] flags) {
191 for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
192 Message m = it.cur();
193 if (what.charAt(0) == 'F') {
194 it.deleted(false); it.seen(false); it.flagged(false); it.draft(false); it.answered(false); it.recent(false); }
195 for(int j=0; j<flags.length; j++) {
196 String flag = flags[j].flag();
197 if (flag.equals("Deleted")) it.deleted(what.charAt(0) != '-');
198 if (flag.equals("Seen")) it.seen(what.charAt(0) != '-');
199 if (flag.equals("Flagged")) it.flagged(what.charAt(0) != '-');
200 if (flag.equals("Draft")) it.draft(what.charAt(0) != '-');
201 if (flag.equals("Answered")) it.answered(what.charAt(0) != '-');
202 if (flag.equals("Recent")) it.recent( what.charAt(0) != '-');
204 selected.add(m); // re-add (?)
208 public boolean handleRequest() throws IOException {
209 LineReader lr = new LineReader(r);
210 pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
215 String s = lr.readLine();
216 if (s.indexOf(' ') == -1) throw new Exn.Bad("BAD Invalid tag");
218 String command = atom();
219 if (command.equals("UID")) { uid = true; command = atom(); }
220 if (command.equals("AUTHENTICATE")) { login(astring(), astring()); }
221 else if (command.equals("LIST")) list(mailbox(), mailboxPattern());
222 else if (command.equals("LSUB")) lsub(mailbox(), mailboxPattern());
223 else if (command.equals("CAPABILITY")) { capability(); }
224 else if (command.equals("LOGIN")) login(astring(), astring());
225 else if (command.equals("LOGOUT")) { logout(); conn.close(); return false; }
226 else if (command.equals("RENAME")) rename(mailbox(), atom());
227 else if (command.equals("APPEND")) append(mailbox(), token());
228 else if (command.equals("EXAMINE")) select(astring(), true);
229 else if (command.equals("SELECT")) select(astring(), false);
230 else if (command.equals("COPY")) copy(Query.num(set()), mailbox());
231 else if (command.equals("DELETE")) delete(mailbox());
232 else if (command.equals("CHECK")) check();
233 else if (command.equals("CREATE")) create(astring());
234 else if (command.equals("STORE")) store(Query.num(set()), atom(), l());
235 else if (command.equals("FETCH")) fetch(Query.num(set()), token());
236 else if (command.equals("STATUS")) status(mailbox(), l());
237 else throw new Exn.Bad("unrecognized command \"" + command + "\"");
238 pw.println(tag + " OK " + command + " Completed.");
239 } catch (Exn.Bad b) { pw.println(tag + " Bad " + b.toString());
240 } catch (Exn.No n) { pw.println(tag + " OK " + n.toString());
247 // Unparsing (printing) logic //////////////////////////////////////////////////////////////////////////////
249 static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
250 static String quotify(Date d) { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
251 static String address(Address a) {return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
252 public static String addressList(Object a) {
253 if (a == null) return "NIL";
254 if (a instanceof Address) return "("+address((Address)a)+")";
255 Address[] aa = (Address[])a;
256 StringBuffer ret = new StringBuffer();
258 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
260 return ret.toString();
262 static String flags(Mailbox.Iterator it) {
264 (it.deleted() ? "\\Deleted " : "") +
265 (it.seen() ? "\\Seen " : "") +
266 (it.flagged() ? "\\Flagged " : "") +
267 (it.draft() ? "\\Draft " : "") +
268 (it.answered() ? "\\Answered " : "") +
269 (it.recent() ? "\\Recent " : "");
271 static String envelope(Message m) {
273 "(" + quotify(m.arrival.toString()) +
274 " " + quotify(m.subject) +
275 " " + addressList(m.from) +
276 " " + addressList(m.headers.get("sender")) +
277 " " + addressList(m.replyto) +
278 " " + addressList(m.to) +
279 " " + addressList(m.cc) +
280 " " + addressList(m.bcc) +
281 " " + quotify((String)m.headers.get("in-reply-to")) +
282 " " + quotify(m.messageid) +
288 // Parsing Logic //////////////////////////////////////////////////////////////////////////////
296 if (t.type == t.LIST) throw new Exn.No("nested queries not yet supported");
297 else if (t.type == t.SET) return Query.num(t.set());
299 if (s.equals("NOT")) { not = true; continue; }
300 if (s.equals("OR")) return Query.or(query(), query());
301 if (s.equals("AND")) return Query.and(query(), query());
304 if (s.startsWith("UN")) { not = true; s = s.substring(2); }
305 if (s.equals("ANSWERED")) q = Query.answered();
306 else if (s.equals("DELETED")) q = Query.deleted();
307 else if (s.equals("DRAFT")) q = Query.draft();
308 else if (s.equals("FLAGGED")) q = Query.flagged();
309 else if (s.equals("RECENT")) q = Query.recent();
310 else if (s.equals("SEEN")) q = Query.seen();
311 else if (s.equals("OLD")) { not = true; q = Query.recent(); }
312 else if (s.equals("NEW")) q = Query.and(Query.recent(), Query.not(Query.seen()));
313 else if (s.equals("KEYWORD")) q = Query.header("keyword", flag());
314 else if (s.equals("HEADER")) q = Query.header(astring(), astring());
315 else if (s.equals("BCC")) q = Query.header("bcc", astring());
316 else if (s.equals("CC")) q = Query.header("cc", astring());
317 else if (s.equals("FROM")) q = Query.header("from", astring());
318 else if (s.equals("TO")) q = Query.header("to", astring());
319 else if (s.equals("SUBJECT")) q = Query.header("subject", astring());
320 else if (s.equals("LARGER")) q = Query.size(n(), Integer.MAX_VALUE);
321 else if (s.equals("SMALLER")) q = Query.size(Integer.MIN_VALUE, n());
322 else if (s.equals("BODY")) q = Query.body(astring());
323 else if (s.equals("TEXT")) q = Query.full(astring());
324 else if (s.equals("BEFORE")) q = Query.arrival(new Date(0), date());
325 else if (s.equals("SINCE")) q = Query.arrival(date(), new Date(Long.MAX_VALUE));
326 else if (s.equals("ON")) { Date d = date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
327 else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), date());
328 else if (s.equals("SENTSINCE")) q = Query.sent(date(), new Date(Long.MAX_VALUE));
329 else if (s.equals("SENTON")) { Date d = date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
330 else if (s.equals("UID")) q = Query.uid(set());
336 private final String s;
337 private final Token[] l;
339 private static final byte NIL = 0;
340 private static final byte LIST = 1;
341 private static final byte QUOTED = 2;
342 private static final byte NUMBER = 3;
343 private static final byte ATOM = 4;
344 private static final byte BAREWORD = 5;
345 private static final byte SET = 6;
346 public Token() { n = 0; l = null; s = null; type = NIL; }
347 public Token(String quoted) { s = quoted; l = null; type = QUOTED; n = 0; }
348 public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
349 public Token(int number) { n = number; l = null; s = null; type = NUMBER; }
351 public String mailboxPattern() throws Exn.Bad {
352 if (type == ATOM) return s;
353 if (type == QUOTED) return s;
354 throw new Exn.Bad("exepected a mailbox pattern");
356 public String flag() throws Exn.Bad {
357 if (type != ATOM) throw new Exn.Bad("expected a flag");
358 return s; // if first char != backslash, it is a keyword-flag
360 public int n() throws Exn.Bad {
361 if (type != NUMBER) throw new Exn.Bad("expected number");
364 public int nz() throws Exn.Bad {
365 if (type != NUMBER) throw new Exn.Bad("expected number");
366 if (n == 0) throw new Exn.Bad("expected nonzero number");
369 public String q() throws Exn.Bad {
370 if (type == NIL) return null;
371 if (type != QUOTED) throw new Exn.Bad("expected qstring");
374 public Token[] l() throws Exn.Bad {
375 if (type == NIL) return null;
376 if (type != LIST) throw new Exn.Bad("expected parenthesized list");
379 public int[] set() throws Exn.Bad {
380 if (type != ATOM) throw new Exn.Bad("expected a messageid set");
382 StringTokenizer st = new StringTokenizer(s, ",");
383 while(st.hasMoreTokens()) {
384 String s = st.nextToken();
385 if (s.indexOf(':') != -1) {
386 int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
387 String end_s = s.substring(s.indexOf(':')+1);
388 if (end_s.equals("*")) {
389 ids.addElement(new Integer(start));
390 ids.addElement(new Integer(-1));
392 int end = Integer.parseInt(end_s);
393 for(int j=start; j<=end; j++) ids.addElement(new Integer(j));
396 ids.addElement(new Integer(Integer.parseInt(s)));
399 int[] ret = new int[ids.size()];
400 for(int i=0; i<ret.length; i++) ret[i] = ((Integer)ids.elementAt(i)).intValue();
403 public Date date() throws Exn.Bad {
404 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted date");
405 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
406 } catch (ParseException p) { throw new Exn.Bad("invalid date format; " + p); }
408 public Date datetime() throws Exn.Bad {
409 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted datetime");
410 try { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").parse(s);
411 } catch (ParseException p) { throw new Exn.Bad("invalid datetime format; " + p); }
413 public String nstring() throws Exn.Bad {
414 if (type == NIL) return null;
415 if (type == QUOTED) return s;
416 throw new Exn.Bad("expected NIL or string");
418 public String astring() throws Exn.Bad {
419 if (type == ATOM) return s;
420 if (type == QUOTED) return s;
421 throw new Exn.Bad("expected atom or string");
423 public String atom() throws Exn.Bad {
424 if (type != ATOM) throw new Exn.Bad("expected atom");
425 for(int i=0; i<s.length(); i++) {
426 char c = s.charAt(i);
427 if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*')
428 throw new Exn.Bad("invalid char in atom: " + c);
432 public Mailbox mailbox() throws Exn.Bad {
433 if (type == BAREWORD && s.toLowerCase().equals("inbox")) return getMailbox("INBOX", false);
434 return getMailbox(astring(), false);
439 public char getc() throws IOException {
441 if (ret == -1) throw new EOFException();
444 public char peekc() throws IOException {
446 if (ret == -1) throw new EOFException();
450 public void fill(byte[] b) throws IOException {
452 while (num < b.length) {
453 int numread = is.read(b, num, b.length - num);
454 if (numread == -1) throw new EOFException();
459 public Token token() {
461 Vec toks = new Vec();
462 StringBuffer sb = new StringBuffer();
463 char c = getc(); while (c == ' ') c = getc();
465 while(peekc() != '}') sb.append(getc());
466 int octets = Integer.parseInt(sb.toString());
467 while(peekc() == ' ') getc(); // whitespace
468 while (getc() != '\n') { }
469 byte[] bytes = new byte[octets];
471 return new Token(new String(bytes));
472 } else if (c == '\"') {
475 if (c == '\\') sb.append(getc());
476 else if (c == '\"') break;
479 return new Token(sb.toString());
480 } else if (c == ')') {
482 } else if (c == '(') {
484 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
485 Token[] ret = new Token[toks.size()];
487 return null; // FIXME
490 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '{') break;
493 return new Token(sb.toString());
494 } catch (IOException e) {
500 // FEATURE: inline these?
501 public String mailboxPattern() throws Exn.Bad { return token().mailboxPattern(); }
502 public String flag() throws Exn.Bad { return token().flag(); }
503 public int n() throws Exn.Bad { return token().n(); }
504 public int nz() throws Exn.Bad { return token().nz(); }
505 public String q() throws Exn.Bad { return token().q(); }
506 public Token[] l() throws Exn.Bad { return token().l(); }
507 public int[] set() throws Exn.Bad { return token().set(); }
508 public Date date() throws Exn.Bad { return token().date(); }
509 public Date datetime() throws Exn.Bad { return token().datetime(); }
510 public String nstring() throws Exn.Bad { return token().nstring(); }
511 public String astring() throws Exn.Bad { return token().astring(); }
512 public String atom() throws Exn.Bad { return token().atom(); }
513 public Mailbox mailbox() throws Exn.Bad, IOException { return token().mailbox(); }