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 == null) { tl = new Token[] { new Token("BODY", false) }; }
164 else if (t.type == Token.LIST) tl = t.l();
165 else if (t.atom().equals("FULL")) full = true;
166 else if (t.atom().equals("ALL")) all = true;
167 else if (t.atom().equals("FAST")) fast = true;
168 StringBuffer reply = new StringBuffer();
169 for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
170 Message m = it.cur();
171 for (int i=0; i<tl.length; i++) {
172 String s = tl[i].atom();
173 if (s.startsWith("BODY.PEEK")) { peek = true; s = "BODY" + s.substring(9); }
174 if (s.startsWith("BODY.1")) s = "BODY" + s.substring(6);
175 if (s.indexOf('<') != -1) {
176 String range = s.substring(s.indexOf('<') + 1, s.indexOf('>'));
177 s = s.substring(0, s.indexOf('<'));
178 if (range.indexOf(imapSeparator) == -1) end = Integer.MAX_VALUE;
180 end = Integer.parseInt(range.substring(range.indexOf(imapSeparator) + 1));
181 range = range.substring(0, range.indexOf(imapSeparator));
183 start = Integer.parseInt(range);
185 if (s.equals("ENVELOPE") || all || full) reply.append("ENVELOPE " + envelope(m) + " ");
186 if (s.equals("FLAGS") || full || all || fast) reply.append("FLAGS (" + flags(it) + ") ");
187 if (s.equals("INTERNALDATE") || full || all || fast) reply.append("INTERNALDATE "+quotify(m.arrival)+" ");
188 if (s.equals("RFC822.SIZE") || full || all || fast) reply.append("RFC822.SIZE " + m.rfc822size() + " ");
189 if (s.equals("RFC822.HEADER") || s.equals("BODY[HEADER]"))
190 { reply.append("BODY[HEADER] {" + m.allHeaders.length() + "}\r\n"); reply.append(m.allHeaders); }
191 if (s.equals("RFC822")||s.equals("RFC822.TEXT")||s.equals("BODY")||s.equals("BODY[]")||s.equals("TEXT")||full)
192 { reply.append("BODY[TEXT] {" + m.body.length() + "}\r\n"); reply.append(m.body); }
193 if (s.equals("UID")) reply.append("UID " + it.uid());
194 if (s.equals("MIME")) throw new Exn.No("FETCH BODY.MIME not supported");
195 if (s.startsWith("BODY[HEADER.FIELDS")) throw new Exn.No("partial headers not supported");
196 if (s.startsWith("BODY[HEADER.FIELDS.NOT")) throw new Exn.No("partial headers not supported");
197 if (s.equals("BODYSTRUCTURE"))
198 reply.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " +
199 m.rfc822size()+" "+ m.lines +")");
201 star(it.num() + " FETCH (" + reply.toString() + ")");
202 // FEATURE: range requests
203 // FEATURE set seen flag if not BODY.PEEK
207 // FEATURE: hoist the parsing here
208 public void store(Query q, String what, Token[] flags) {
209 for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
210 Message m = it.cur();
211 if (what.charAt(0) == 'F') {
212 it.deleted(false); it.seen(false); it.flagged(false); it.draft(false); it.answered(false); it.recent(false); }
213 for(int j=0; j<flags.length; j++) {
214 String flag = flags[j].flag();
215 if (flag.equals("Deleted")) it.deleted(what.charAt(0) != '-');
216 if (flag.equals("Seen")) it.seen(what.charAt(0) != '-');
217 if (flag.equals("Flagged")) it.flagged(what.charAt(0) != '-');
218 if (flag.equals("Draft")) it.draft(what.charAt(0) != '-');
219 if (flag.equals("Answered")) it.answered(what.charAt(0) != '-');
220 if (flag.equals("Recent")) it.recent( what.charAt(0) != '-');
222 selected.add(m); // re-add (?)
226 public boolean handleRequest() throws IOException {
227 pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
228 System.err.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
235 // FIXME better error if atom() fails
237 String command = atom();
238 if (command.equalsIgnoreCase("UID")) { uid = true; command = atom(); }
239 if (command.equalsIgnoreCase("AUTHENTICATE")) { login(astring(), astring()); }
240 else if (command.equalsIgnoreCase("LIST")) list(mailbox(), mailboxPattern());
241 else if (command.equalsIgnoreCase("LSUB")) lsub(mailbox(), mailboxPattern());
242 else if (command.equalsIgnoreCase("CAPABILITY")) { capability(); }
243 else if (command.equalsIgnoreCase("LOGIN")) login(astring(), astring());
244 else if (command.equalsIgnoreCase("LOGOUT")) { logout(); conn.close(); return false; }
245 else if (command.equalsIgnoreCase("RENAME")) rename(mailbox(), atom());
246 else if (command.equalsIgnoreCase("APPEND")) append(mailbox(), token());
247 else if (command.equalsIgnoreCase("EXAMINE")) select(astring(), true);
248 else if (command.equalsIgnoreCase("SELECT")) select(astring(), false);
249 else if (command.equalsIgnoreCase("COPY")) copy(Query.num(set()), mailbox());
250 else if (command.equalsIgnoreCase("DELETE")) delete(mailbox());
251 else if (command.equalsIgnoreCase("CHECK")) check();
252 else if (command.equalsIgnoreCase("NOOP")) noop();
253 else if (command.equalsIgnoreCase("CREATE")) create(astring());
254 else if (command.equalsIgnoreCase("STORE")) store(Query.num(set()), atom(), l());
255 else if (command.equalsIgnoreCase("FETCH")) fetch(Query.num(set()), token());
256 else if (command.equalsIgnoreCase("STATUS")) status(mailbox(), l());
257 else throw new Exn.Bad("unrecognized command \"" + command + "\"");
258 pw.println(tag + " OK " + command + " Completed.");
259 System.err.println(tag + " OK " + command + " Completed.");
260 } catch (Exn.Bad b) { pw.println(tag + " Bad " + b.toString()); System.err.println(tag + " Bad " + b.toString()); b.printStackTrace();
261 } catch (Exn.No n) { pw.println(tag + " OK " + n.toString()); System.err.println(tag + " OK " + n.toString());
269 // Unparsing (printing) logic //////////////////////////////////////////////////////////////////////////////
271 static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
272 static String quotify(Date d) { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
273 static String address(Address a) {return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
274 public static String addressList(Object a) {
275 if (a == null) return "NIL";
276 if (a instanceof Address) return "("+address((Address)a)+")";
277 Address[] aa = (Address[])a;
278 StringBuffer ret = new StringBuffer();
280 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
282 return ret.toString();
284 static String flags(Mailbox.Iterator it) {
286 (it.deleted() ? "\\Deleted " : "") +
287 (it.seen() ? "\\Seen " : "") +
288 (it.flagged() ? "\\Flagged " : "") +
289 (it.draft() ? "\\Draft " : "") +
290 (it.answered() ? "\\Answered " : "") +
291 (it.recent() ? "\\Recent " : "");
293 static String envelope(Message m) {
295 "(" + quotify(m.arrival.toString()) +
296 " " + quotify(m.subject) +
297 " " + addressList(m.from) +
298 " " + addressList(m.headers.get("sender")) +
299 " " + addressList(m.replyto) +
300 " " + addressList(m.to) +
301 " " + addressList(m.cc) +
302 " " + addressList(m.bcc) +
303 " " + quotify((String)m.headers.get("in-reply-to")) +
304 " " + quotify(m.messageid) +
310 // Parsing Logic //////////////////////////////////////////////////////////////////////////////
318 if (t.type == t.LIST) throw new Exn.No("nested queries not yet supported");
319 else if (t.type == t.SET) return Query.num(t.set());
321 if (s.equals("NOT")) { not = true; continue; }
322 if (s.equals("OR")) return Query.or(query(), query());
323 if (s.equals("AND")) return Query.and(query(), query());
326 if (s.startsWith("UN")) { not = true; s = s.substring(2); }
327 if (s.equals("ANSWERED")) q = Query.answered();
328 else if (s.equals("DELETED")) q = Query.deleted();
329 else if (s.equals("DRAFT")) q = Query.draft();
330 else if (s.equals("FLAGGED")) q = Query.flagged();
331 else if (s.equals("RECENT")) q = Query.recent();
332 else if (s.equals("SEEN")) q = Query.seen();
333 else if (s.equals("OLD")) { not = true; q = Query.recent(); }
334 else if (s.equals("NEW")) q = Query.and(Query.recent(), Query.not(Query.seen()));
335 else if (s.equals("KEYWORD")) q = Query.header("keyword", flag());
336 else if (s.equals("HEADER")) q = Query.header(astring(), astring());
337 else if (s.equals("BCC")) q = Query.header("bcc", astring());
338 else if (s.equals("CC")) q = Query.header("cc", astring());
339 else if (s.equals("FROM")) q = Query.header("from", astring());
340 else if (s.equals("TO")) q = Query.header("to", astring());
341 else if (s.equals("SUBJECT")) q = Query.header("subject", astring());
342 else if (s.equals("LARGER")) q = Query.size(n(), Integer.MAX_VALUE);
343 else if (s.equals("SMALLER")) q = Query.size(Integer.MIN_VALUE, n());
344 else if (s.equals("BODY")) q = Query.body(astring());
345 else if (s.equals("TEXT")) q = Query.full(astring());
346 else if (s.equals("BEFORE")) q = Query.arrival(new Date(0), date());
347 else if (s.equals("SINCE")) q = Query.arrival(date(), new Date(Long.MAX_VALUE));
348 else if (s.equals("ON")) { Date d = date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
349 else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), date());
350 else if (s.equals("SENTSINCE")) q = Query.sent(date(), new Date(Long.MAX_VALUE));
351 else if (s.equals("SENTON")) { Date d = date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
352 else if (s.equals("UID")) q = Query.uid(set());
358 private final String s;
359 private final Token[] l;
361 private static final byte NIL = 0;
362 private static final byte LIST = 1;
363 private static final byte QUOTED = 2;
364 private static final byte NUMBER = 3;
365 private static final byte ATOM = 4;
366 private static final byte BAREWORD = 5;
367 private static final byte SET = 6;
368 public Token() { n = 0; l = null; s = null; type = NIL; }
369 public Token(String s, boolean quoted) { this.s = s; l = null; type = quoted ? QUOTED : ATOM; n = 0; }
370 public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
371 public Token(int number) { n = number; l = null; s = null; type = NUMBER; }
373 public String mailboxPattern() throws Exn.Bad {
374 if (type == ATOM) return s;
375 if (type == QUOTED) return s;
376 throw new Exn.Bad("exepected a mailbox pattern");
378 public String flag() throws Exn.Bad {
379 if (type != ATOM) throw new Exn.Bad("expected a flag");
380 return s; // if first char != backslash, it is a keyword-flag
382 public int n() throws Exn.Bad {
383 if (type != NUMBER) throw new Exn.Bad("expected number");
386 public int nz() throws Exn.Bad {
387 if (type != NUMBER) throw new Exn.Bad("expected number");
388 if (n == 0) throw new Exn.Bad("expected nonzero number");
391 public String q() throws Exn.Bad {
392 if (type == NIL) return null;
393 if (type != QUOTED) throw new Exn.Bad("expected qstring");
396 public Token[] l() throws Exn.Bad {
397 if (type == NIL) return null;
398 if (type != LIST) throw new Exn.Bad("expected parenthesized list");
401 public int[] set() throws Exn.Bad {
402 if (type != ATOM) throw new Exn.Bad("expected a messageid set");
404 StringTokenizer st = new StringTokenizer(s, ",");
405 while(st.hasMoreTokens()) {
406 String s = st.nextToken();
407 if (s.indexOf(':') != -1) {
408 int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
409 String end_s = s.substring(s.indexOf(':')+1);
410 if (end_s.equals("*")) {
411 ids.addElement(new Integer(start));
412 ids.addElement(new Integer(-1));
414 int end = Integer.parseInt(end_s);
415 for(int j=start; j<=end; j++) ids.addElement(new Integer(j));
418 ids.addElement(new Integer(Integer.parseInt(s)));
421 int[] ret = new int[ids.size()];
422 for(int i=0; i<ret.length; i++) ret[i] = ((Integer)ids.elementAt(i)).intValue();
425 public Date date() throws Exn.Bad {
426 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted date");
427 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
428 } catch (ParseException p) { throw new Exn.Bad("invalid date format; " + p); }
430 public Date datetime() throws Exn.Bad {
431 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted datetime");
432 try { return new SimpleDateFormat("dd-MM-yyyy hh:mm:ss").parse(s.trim());
433 } catch (ParseException p) { throw new Exn.Bad("invalid datetime format " + s + " : " + p); }
435 public String nstring() throws Exn.Bad {
436 if (type == NIL) return null;
437 if (type == QUOTED) return s;
438 throw new Exn.Bad("expected NIL or string");
440 public String astring() throws Exn.Bad {
441 if (type == ATOM) return s;
442 if (type == QUOTED) return s;
443 throw new Exn.Bad("expected atom or string");
445 public String atom() throws Exn.Bad {
446 if (type != ATOM) throw new Exn.Bad("expected atom");
447 for(int i=0; i<s.length(); i++) {
448 char c = s.charAt(i);
449 if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*')
450 throw new Exn.Bad("invalid char in atom: " + c);
454 public Mailbox mailbox() throws Exn.Bad {
455 if (type == BAREWORD && s.toLowerCase().equals("inbox")) return getMailbox("INBOX", false);
456 return getMailbox(astring(), false);
461 public char getc() throws IOException {
463 if (ret == -1) throw new EOFException();
464 System.err.print((char)ret);
468 public char peekc() throws IOException {
470 if (ret == -1) throw new EOFException();
474 public void fill(byte[] b) throws IOException {
476 while (num < b.length) {
477 int numread = is.read(b, num, b.length - num);
478 if (numread == -1) throw new EOFException();
483 public void newline() {
485 for(char c = peekc(); c == ' ';) { getc(); c = peekc(); };
486 for(char c = peekc(); c == '\r' || c == '\n';) { getc(); c = peekc(); };
487 } catch (IOException e) {
492 public Token token() {
494 Vec toks = new Vec();
495 StringBuffer sb = new StringBuffer();
496 char c = getc(); while (c == ' ') c = getc();
497 if (c == '\r' || c == '\n') {
498 throw new Exn.Bad("unexpected end of line");
500 while(peekc() != '}') sb.append(getc());
501 int octets = Integer.parseInt(sb.toString());
502 while(peekc() == ' ') getc(); // whitespace
503 while (getc() != '\n' && getc() != '\r') { }
504 byte[] bytes = new byte[octets];
506 return new Token(new String(bytes), true);
507 } else if (c == '\"') {
510 if (c == '\\') sb.append(getc());
511 else if (c == '\"') break;
514 return new Token(sb.toString(), true);
515 } else if (c == ')') {
517 } else if (c == '(') {
519 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
520 Token[] ret = new Token[toks.size()];
522 return null; // FIXME
526 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '{' || c == '\n' || c == '\r')
527 return new Token(sb.toString(), false);
530 } catch (IOException e) {
536 // FEATURE: inline these?
537 public String mailboxPattern() throws Exn.Bad { return token().mailboxPattern(); }
538 public String flag() throws Exn.Bad { return token().flag(); }
539 public int n() throws Exn.Bad { return token().n(); }
540 public int nz() throws Exn.Bad { return token().nz(); }
541 public String q() throws Exn.Bad { return token().q(); }
542 public Token[] l() throws Exn.Bad { return token().l(); }
543 public int[] set() throws Exn.Bad { return token().set(); }
544 public Date date() throws Exn.Bad { return token().date(); }
545 public Date datetime() throws Exn.Bad { return token().datetime(); }
546 public String nstring() throws Exn.Bad { return token().nstring(); }
547 public String astring() throws Exn.Bad { return token().astring(); }
548 public String atom() throws Exn.Bad { return token().atom(); }
549 public Mailbox mailbox() throws Exn.Bad, IOException { return token().mailbox(); }