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) {
67 System.err.println("* " + s);
71 // FIXME: user-inbox-relative stuff
72 // FIXME should throw a No if mailbox not found and create==false
73 private Mailbox getMailbox(String name, boolean create) {
75 while(name.length() > 0) {
76 int end = name.length();
77 if (name.indexOf(imapSeparator) != -1) end = name.indexOf(imapSeparator);
78 m = m.slash(name.substring(0, end), create);
79 if (end == name.length()) break;
80 name = name.substring(end+1);
85 private boolean auth(String user, String pass) { /* FEATURE */ return user.equals("megacz") && pass.equals("pass"); }
87 // FEATURE: manage subscriptions
88 public void lsub(Mailbox m, String s) {
89 star("LSUB () \".\" INBOX");
93 public void list(Mailbox m, String s) {
94 //star("LIST () \".\" INBOX");
95 star("LIST () \".\" users.megacz.imap");
98 public void copy(final Query q, Mailbox to) { for(Mailbox.Iterator it=selected.iterator(q);it.next();) to.add(it.cur()); }
99 public void login(String user, String pass) { if (!auth(user, pass)) throw new Exn.No("Liar, liar, pants on fire."); }
100 public void capability() { star("CAPABILITY IMAP4rev1"); }
101 public void logout() { star("BYE LOGOUT received"); }
102 public void delete(Mailbox m) { if (!m.equals(inbox)) m.destroy(); }
103 public void create(String mailbox){if(!mailbox.endsWith(".")&&!mailbox.equalsIgnoreCase("inbox"))getMailbox(mailbox,true);}
104 public void close(boolean examineOnly) { expunge(false, true); selected = null; }
105 public void check() { }
106 public void noop() { }
108 public void rename(Mailbox from, String to) {
109 if (from.equals(inbox)) from.copy(Query.all(), getMailbox(to, true));
110 else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), getMailbox(to, true)); from.destroy(); }
111 else from.rename(to);
114 public void status(final Mailbox m, Token[] attrs) {
115 int count0 = 0, count1 = 0, count2 = 0;
116 for(Mailbox.Iterator it = m.iterator(); it.next(); ) { if (!it.seen()) count0++; if (it.recent()) count1++; count2++; }
117 String response = "";
118 for(int i=0; i<attrs.length; i++) {
119 String s = attrs[i].atom();
120 if (s.equals("MESSAGES")) response += "MESSAGES " + count2;
121 if (s.equals("RECENT")) response += "RECENT " + count0;
122 if (s.equals("UIDNEXT")) response += "UNSEEN " + count1;
123 if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + m.uidValidity();
124 if (s.equals("UNSEEN")) response += "UIDNEXT " + m.uidNext();
126 star("STATUS " + /* FIXME m.getName() +*/ " (" + response + ")");
129 public void select(String mailbox, boolean examineOnly) {
130 selected = getMailbox(mailbox, false);
131 if (selected == null) throw new Exn.No("no such mailbox"); // should this be 'Bad'?
132 star(selected.count(Query.all()) + " EXISTS");
133 star(selected.count(Query.recent()) + " RECENT");
134 //star("OK [UNSEEN 12] Message 12 is first unseen"); FEATURE
135 star("OK [UIDVALIDITY " + selected.uidValidity() + "] UIDs valid");
136 star("FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
137 // FEATURE: READ-WRITE / READ-ONLY
140 public void expunge(final boolean examineOnly, final boolean silent) {
141 if (selected == null) throw new Exn.Bad("no mailbox selected");
142 for(Mailbox.Iterator it = selected.iterator(); it.next();) {
143 if (!it.deleted()) return;
144 if (!silent) star(it.uid() + " EXPUNGE");
145 if (!examineOnly) it.delete();
149 public void append(Mailbox m, Token t) {
150 Token[] flags = null;
152 if (t.type == t.LIST) { flags = t.l(); t = token(); }
153 if (t.type == t.QUOTED) { arrival = t.datetime(); t = token(); }
154 String literal = q();
155 m.add(new Message(null, new Address[] { null }, new LineReader(new StringReader(literal))));
156 if (flags != null) { /* FEATURE */ }
159 public void fetch(Query q, Token t) {
161 int start = -1, end = -1;
162 boolean peek = false, fast = false, all = false, full = false;
163 if (t.type == Token.LIST) tl = t.l();
164 else if (t.atom().equals("FULL")) full = true;
165 else if (t.atom().equals("ALL")) all = true;
166 else if (t.atom().equals("FAST")) fast = true;
167 StringBuffer reply = new StringBuffer();
168 for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
169 Message m = it.cur();
170 for (int i=0; i<tl.length; i++) {
171 String s = tl[i].atom();
172 if (s.startsWith("BODY.PEEK")) { peek = true; s = "BODY" + s.substring(9); }
173 if (s.startsWith("BODY.1")) s = "BODY" + s.substring(6);
174 if (s.indexOf('<') != -1) {
175 String range = s.substring(s.indexOf('<') + 1, s.indexOf('>'));
176 s = s.substring(0, s.indexOf('<'));
177 if (range.indexOf(imapSeparator) == -1) end = Integer.MAX_VALUE;
179 end = Integer.parseInt(range.substring(range.indexOf(imapSeparator) + 1));
180 range = range.substring(0, range.indexOf(imapSeparator));
182 start = Integer.parseInt(range);
184 if (s.equals("ENVELOPE") || all || full) reply.append("ENVELOPE " + envelope(m) + " ");
185 if (s.equals("FLAGS") || full || all || fast) reply.append("FLAGS (" + flags(it) + ") ");
186 if (s.equals("INTERNALDATE") || full || all || fast) reply.append("INTERNALDATE "+quotify(m.arrival)+" ");
187 if (s.equals("RFC822.SIZE") || full || all || fast) reply.append("RFC822.SIZE " + m.rfc822size() + " ");
188 if (s.equals("RFC822.HEADER") || s.equals("BODY[HEADER]"))
189 { reply.append("BODY[HEADER] {" + m.allHeaders.length() + "}\r\n"); reply.append(m.allHeaders); }
190 if (s.equals("RFC822")||s.equals("RFC822.TEXT")||s.equals("BODY")||s.equals("BODY[]")||s.equals("TEXT")||full)
191 { reply.append("BODY[TEXT] {" + m.body.length() + "}\r\n"); reply.append(m.body); }
192 if (s.equals("UID")) reply.append("UID " + it.uid());
193 if (s.equals("MIME")) throw new Exn.No("FETCH BODY.MIME not supported");
194 if (s.startsWith("BODY[HEADER.FIELDS")) throw new Exn.No("partial headers not supported");
195 if (s.startsWith("BODY[HEADER.FIELDS.NOT")) throw new Exn.No("partial headers not supported");
196 if (s.equals("BODYSTRUCTURE"))
197 reply.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " +
198 m.rfc822size()+" "+ m.lines +")");
200 star(it.num() + " FETCH (" + reply.toString() + ")");
201 // FEATURE: range requests
202 // FEATURE set seen flag if not BODY.PEEK
206 // FEATURE: hoist the parsing here
207 public void store(Query q, String what, Token[] flags) {
208 for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
209 Message m = it.cur();
210 if (what.charAt(0) == 'F') {
211 it.deleted(false); it.seen(false); it.flagged(false); it.draft(false); it.answered(false); it.recent(false); }
212 for(int j=0; j<flags.length; j++) {
213 String flag = flags[j].flag();
214 if (flag.equals("Deleted")) it.deleted(what.charAt(0) != '-');
215 if (flag.equals("Seen")) it.seen(what.charAt(0) != '-');
216 if (flag.equals("Flagged")) it.flagged(what.charAt(0) != '-');
217 if (flag.equals("Draft")) it.draft(what.charAt(0) != '-');
218 if (flag.equals("Answered")) it.answered(what.charAt(0) != '-');
219 if (flag.equals("Recent")) it.recent( what.charAt(0) != '-');
221 selected.add(m); // re-add (?)
225 public boolean handleRequest() throws IOException {
226 pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
227 System.err.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
234 // FIXME better error if atom() fails
236 String command = atom();
237 if (command.equalsIgnoreCase("UID")) { uid = true; command = atom(); }
238 if (command.equalsIgnoreCase("AUTHENTICATE")) { login(astring(), astring()); }
239 else if (command.equalsIgnoreCase("LIST")) list(mailbox(), mailboxPattern());
240 else if (command.equalsIgnoreCase("LSUB")) lsub(mailbox(), mailboxPattern());
241 else if (command.equalsIgnoreCase("CAPABILITY")) { capability(); }
242 else if (command.equalsIgnoreCase("LOGIN")) login(astring(), astring());
243 else if (command.equalsIgnoreCase("LOGOUT")) { logout(); conn.close(); return false; }
244 else if (command.equalsIgnoreCase("RENAME")) rename(mailbox(), atom());
245 else if (command.equalsIgnoreCase("APPEND")) append(mailbox(), token());
246 else if (command.equalsIgnoreCase("EXAMINE")) select(astring(), true);
247 else if (command.equalsIgnoreCase("SELECT")) select(astring(), false);
248 else if (command.equalsIgnoreCase("COPY")) copy(Query.num(set()), mailbox());
249 else if (command.equalsIgnoreCase("DELETE")) delete(mailbox());
250 else if (command.equalsIgnoreCase("CHECK")) check();
251 else if (command.equalsIgnoreCase("NOOP")) noop();
252 else if (command.equalsIgnoreCase("CREATE")) create(astring());
253 else if (command.equalsIgnoreCase("STORE")) store(Query.num(set()), atom(), l());
254 else if (command.equalsIgnoreCase("FETCH")) fetch(Query.num(set()), token());
255 else if (command.equalsIgnoreCase("STATUS")) status(mailbox(), l());
256 else throw new Exn.Bad("unrecognized command \"" + command + "\"");
257 pw.println(tag + " OK " + command + " Completed.");
258 System.err.println(tag + " OK " + command + " Completed.");
259 } catch (Exn.Bad b) { pw.println(tag + " Bad " + b.toString()); System.err.println(tag + " Bad " + b.toString()); b.printStackTrace();
260 } catch (Exn.No n) { pw.println(tag + " OK " + n.toString()); System.err.println(tag + " OK " + n.toString());
268 // Unparsing (printing) logic //////////////////////////////////////////////////////////////////////////////
270 static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
271 static String quotify(Date d) { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
272 static String address(Address a) {return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
273 public static String addressList(Object a) {
274 if (a == null) return "NIL";
275 if (a instanceof Address) return "("+address((Address)a)+")";
276 Address[] aa = (Address[])a;
277 StringBuffer ret = new StringBuffer();
279 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
281 return ret.toString();
283 static String flags(Mailbox.Iterator it) {
285 (it.deleted() ? "\\Deleted " : "") +
286 (it.seen() ? "\\Seen " : "") +
287 (it.flagged() ? "\\Flagged " : "") +
288 (it.draft() ? "\\Draft " : "") +
289 (it.answered() ? "\\Answered " : "") +
290 (it.recent() ? "\\Recent " : "");
292 static String envelope(Message m) {
294 "(" + quotify(m.arrival.toString()) +
295 " " + quotify(m.subject) +
296 " " + addressList(m.from) +
297 " " + addressList(m.headers.get("sender")) +
298 " " + addressList(m.replyto) +
299 " " + addressList(m.to) +
300 " " + addressList(m.cc) +
301 " " + addressList(m.bcc) +
302 " " + quotify((String)m.headers.get("in-reply-to")) +
303 " " + quotify(m.messageid) +
309 // Parsing Logic //////////////////////////////////////////////////////////////////////////////
317 if (t.type == t.LIST) throw new Exn.No("nested queries not yet supported");
318 else if (t.type == t.SET) return Query.num(t.set());
320 if (s.equals("NOT")) { not = true; continue; }
321 if (s.equals("OR")) return Query.or(query(), query());
322 if (s.equals("AND")) return Query.and(query(), query());
325 if (s.startsWith("UN")) { not = true; s = s.substring(2); }
326 if (s.equals("ANSWERED")) q = Query.answered();
327 else if (s.equals("DELETED")) q = Query.deleted();
328 else if (s.equals("DRAFT")) q = Query.draft();
329 else if (s.equals("FLAGGED")) q = Query.flagged();
330 else if (s.equals("RECENT")) q = Query.recent();
331 else if (s.equals("SEEN")) q = Query.seen();
332 else if (s.equals("OLD")) { not = true; q = Query.recent(); }
333 else if (s.equals("NEW")) q = Query.and(Query.recent(), Query.not(Query.seen()));
334 else if (s.equals("KEYWORD")) q = Query.header("keyword", flag());
335 else if (s.equals("HEADER")) q = Query.header(astring(), astring());
336 else if (s.equals("BCC")) q = Query.header("bcc", astring());
337 else if (s.equals("CC")) q = Query.header("cc", astring());
338 else if (s.equals("FROM")) q = Query.header("from", astring());
339 else if (s.equals("TO")) q = Query.header("to", astring());
340 else if (s.equals("SUBJECT")) q = Query.header("subject", astring());
341 else if (s.equals("LARGER")) q = Query.size(n(), Integer.MAX_VALUE);
342 else if (s.equals("SMALLER")) q = Query.size(Integer.MIN_VALUE, n());
343 else if (s.equals("BODY")) q = Query.body(astring());
344 else if (s.equals("TEXT")) q = Query.full(astring());
345 else if (s.equals("BEFORE")) q = Query.arrival(new Date(0), date());
346 else if (s.equals("SINCE")) q = Query.arrival(date(), new Date(Long.MAX_VALUE));
347 else if (s.equals("ON")) { Date d = date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
348 else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), date());
349 else if (s.equals("SENTSINCE")) q = Query.sent(date(), new Date(Long.MAX_VALUE));
350 else if (s.equals("SENTON")) { Date d = date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
351 else if (s.equals("UID")) q = Query.uid(set());
357 private final String s;
358 private final Token[] l;
360 private static final byte NIL = 0;
361 private static final byte LIST = 1;
362 private static final byte QUOTED = 2;
363 private static final byte NUMBER = 3;
364 private static final byte ATOM = 4;
365 private static final byte BAREWORD = 5;
366 private static final byte SET = 6;
367 public Token() { n = 0; l = null; s = null; type = NIL; }
368 public Token(String s, boolean quoted) { this.s = s; l = null; type = quoted ? QUOTED : ATOM; n = 0; }
369 public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
370 public Token(int number) { n = number; l = null; s = null; type = NUMBER; }
372 public String mailboxPattern() throws Exn.Bad {
373 if (type == ATOM) return s;
374 if (type == QUOTED) return s;
375 throw new Exn.Bad("exepected a mailbox pattern");
377 public String flag() throws Exn.Bad {
378 if (type != ATOM) throw new Exn.Bad("expected a flag");
379 return s; // if first char != backslash, it is a keyword-flag
381 public int n() throws Exn.Bad {
382 if (type != NUMBER) throw new Exn.Bad("expected number");
385 public int nz() throws Exn.Bad {
386 if (type != NUMBER) throw new Exn.Bad("expected number");
387 if (n == 0) throw new Exn.Bad("expected nonzero number");
390 public String q() throws Exn.Bad {
391 if (type == NIL) return null;
392 if (type != QUOTED) throw new Exn.Bad("expected qstring");
395 public Token[] l() throws Exn.Bad {
396 if (type == NIL) return null;
397 if (type != LIST) throw new Exn.Bad("expected parenthesized list");
400 public int[] set() throws Exn.Bad {
401 if (type != ATOM) throw new Exn.Bad("expected a messageid set");
403 StringTokenizer st = new StringTokenizer(s, ",");
404 while(st.hasMoreTokens()) {
405 String s = st.nextToken();
406 if (s.indexOf(':') != -1) {
407 int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
408 String end_s = s.substring(s.indexOf(':')+1);
409 if (end_s.equals("*")) {
410 ids.addElement(new Integer(start));
411 ids.addElement(new Integer(-1));
413 int end = Integer.parseInt(end_s);
414 for(int j=start; j<=end; j++) ids.addElement(new Integer(j));
417 ids.addElement(new Integer(Integer.parseInt(s)));
420 int[] ret = new int[ids.size()];
421 for(int i=0; i<ret.length; i++) ret[i] = ((Integer)ids.elementAt(i)).intValue();
424 public Date date() throws Exn.Bad {
425 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted date");
426 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
427 } catch (ParseException p) { throw new Exn.Bad("invalid date format; " + p); }
429 public Date datetime() throws Exn.Bad {
430 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted datetime");
431 try { return new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").parse(s.trim());
432 } catch (ParseException p) { throw new Exn.Bad("invalid datetime format " + s + " : " + p); }
434 public String nstring() throws Exn.Bad {
435 if (type == NIL) return null;
436 if (type == QUOTED) return s;
437 throw new Exn.Bad("expected NIL or string");
439 public String astring() throws Exn.Bad {
440 if (type == ATOM) return s;
441 if (type == QUOTED) return s;
442 throw new Exn.Bad("expected atom or string");
444 public String atom() throws Exn.Bad {
445 if (type != ATOM) throw new Exn.Bad("expected atom");
446 for(int i=0; i<s.length(); i++) {
447 char c = s.charAt(i);
448 if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*')
449 throw new Exn.Bad("invalid char in atom: " + c);
453 public Mailbox mailbox() throws Exn.Bad {
454 if (type == BAREWORD && s.toLowerCase().equals("inbox")) return getMailbox("INBOX", false);
455 return getMailbox(astring(), false);
460 public char getc() throws IOException {
462 if (ret == -1) throw new EOFException();
463 System.err.print((char)ret);
467 public char peekc() throws IOException {
469 if (ret == -1) throw new EOFException();
473 public void fill(byte[] b) throws IOException {
475 while (num < b.length) {
476 int numread = is.read(b, num, b.length - num);
477 if (numread == -1) throw new EOFException();
482 public void newline() {
484 for(char c = peekc(); c == ' ';) { getc(); c = peekc(); };
485 for(char c = peekc(); c == '\r' || c == '\n';) { getc(); c = peekc(); };
486 } catch (IOException e) {
491 public Token token() {
493 Vec toks = new Vec();
494 StringBuffer sb = new StringBuffer();
495 char c = getc(); while (c == ' ') c = getc();
496 if (c == '\r' || c == '\n') {
497 throw new Exn.Bad("unexpected end of line");
499 while(peekc() != '}') sb.append(getc());
500 int octets = Integer.parseInt(sb.toString());
501 while(peekc() == ' ') getc(); // whitespace
502 while (getc() != '\n' && getc() != '\r') { }
503 byte[] bytes = new byte[octets];
505 return new Token(new String(bytes), true);
506 } else if (c == '\"') {
509 if (c == '\\') sb.append(getc());
510 else if (c == '\"') break;
513 return new Token(sb.toString(), true);
514 } else if (c == ')') {
516 } else if (c == '(') {
518 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
519 Token[] ret = new Token[toks.size()];
521 return null; // FIXME
525 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '{' || c == '\n' || c == '\r')
526 return new Token(sb.toString(), false);
529 } catch (IOException e) {
535 // FEATURE: inline these?
536 public String mailboxPattern() throws Exn.Bad { return token().mailboxPattern(); }
537 public String flag() throws Exn.Bad { return token().flag(); }
538 public int n() throws Exn.Bad { return token().n(); }
539 public int nz() throws Exn.Bad { return token().nz(); }
540 public String q() throws Exn.Bad { return token().q(); }
541 public Token[] l() throws Exn.Bad { return token().l(); }
542 public int[] set() throws Exn.Bad { return token().set(); }
543 public Date date() throws Exn.Bad { return token().date(); }
544 public Date datetime() throws Exn.Bad { return token().datetime(); }
545 public String nstring() throws Exn.Bad { return token().nstring(); }
546 public String astring() throws Exn.Bad { return token().astring(); }
547 public String atom() throws Exn.Bad { return token().atom(); }
548 public Mailbox mailbox() throws Exn.Bad, IOException { return token().mailbox(); }