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 void main(String[] args) throws Exception {
16 ServerSocket ss = new ServerSocket(143);
18 System.out.println("listening");
19 final Socket s = ss.accept();
20 System.out.println("connected");
24 new Listener(s, "megacz.com").handleRequest();
25 } catch (Exception e) {
33 public static class Exn extends MailException {
34 public Exn(String s) { super(s); }
35 public static class No extends Exn { public No(String s) { super(s); } }
36 public static class Bad extends Exn { public Bad(String s) { super(s); } }
39 private static class Listener extends Incoming {
40 Mailbox selected = null;
48 public void init() { }
49 public Listener(Socket conn, String vhost) throws IOException {
53 this.pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
54 this.is = conn.getInputStream();
55 this.r = new PushbackReader(new InputStreamReader(is));
58 // ugly: not concurrent
60 private void ok(String s) { pw.println(tag + " OK " + s); }
61 private void star(String s) { pw.println("* " + s); }
63 // FIXME should throw a No if mailbox not found and create==false
64 private Mailbox getMailbox(String name, boolean create) {
66 while(name.length() > 0) {
67 int end = name.length();
68 if (name.indexOf('.') != -1) end = name.indexOf('.');
69 m = m.slash(name.substring(0, end), create);
70 name = name.substring(end);
75 public void lsub(Mailbox m, String s) { star("LIST () \".\" INBOX"); ok("LSUB completed"); } // FIXME
76 public void list(Mailbox m, String s) { star("LIST () \".\" INBOX"); ok("LIST completed"); } // FIXME
78 private boolean auth(String user, String pass) { /* FEATURE */ return user.equals("megacz") && pass.equals(""); }
79 public void copy(final Query q, final Mailbox target) {
80 for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) { target.add(it.cur()); } }
81 public void login(String user, String password) {if (!auth(user,password))throw new Exn.No("Liar, liar, pants on fire."); }
82 public void capability() { star("CAPABILITY IMAP4rev1"); ok("Completed"); }
83 public void noop() { ok("Completed"); }
84 public void logout() { star("BYE LOGOUT received"); ok("Completed"); }
87 public void delete(Mailbox m) { /*if (!m.getName().toLowerCase().equals("inbox")) m.destroy(); ok("Completed");*/ }
89 public void subscribe(String[] args) { ok("SUBSCRIBE ignored"); }
90 public void unsubscribe(String[] args) { ok("UNSUBSCRIBE ignored"); }
91 public void check() { ok("CHECK ignored"); }
94 public void create(String mailbox){/*if(!mailbox.endsWith(".")&&!mailbox.equalsIgnoreCase("inbox"))getMailbox(mailbox,true);*/}
97 public void rename(Mailbox from, String to) {
99 if (from.getName().equalsIgnoreCase("inbox")) from.moveAllMessagesTo(getMailbox(to, true));
100 else if (to.equalsIgnoreCase("inbox")) { from.moveAllMessagesTo(getMailbox(to, true)); from.destroy(); }
101 else*/ from.rename(to);
104 public void status(final Mailbox m, Token[] attrs) {
105 int count0 = 0, count1 = 0, count2 = 0;
106 for(Mailbox.Iterator it = m.iterator(); it.next(); ) {
107 if (!it.seen()) count0++;
108 if (it.recent()) count1++;
111 String response = "";
112 for(int i=0; i<attrs.length; i++) {
113 String s = attrs[i].atom();
114 if (s.equals("MESSAGES")) response += "MESSAGES " + count2;
115 if (s.equals("RECENT")) response += "RECENT " + count0;
116 if (s.equals("UIDNEXT")) response += "UNSEEN " + count1;
117 if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + m.uidValidity();
118 if (s.equals("UNSEEN")) response += "UIDNEXT " + m.uidNext();
120 star("STATUS " + m.getName() + " (" + response + ")");
123 public void select(String mailbox, boolean examineOnly) {
124 selected = getMailbox(mailbox, false);
125 star(selected.count(Query.all()) + " EXISTS");
127 for(Mailbox.Iterator it = selected.iterator(); it.next(); ) { if (it.recent()) recent++; }
128 star(recent + " RECENT");
129 //star("OK [UNSEEN 12] Message 12 is first unseen"); FEATURE
130 star("OK [UIDVALIDITY " + selected.uidValidity() + "] UIDs valid");
131 star("FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
132 // FEATURE: READ-WRITE / READ-ONLY
133 ok((examineOnly ? "EXAMINE" : "SELECT") + " completed");
136 public void close(boolean examineOnly) {
137 if (selected == null) throw new Exn.Bad("no mailbox selected");
138 expunge(false, true);
140 ok("CLOSE completed");
143 public void expunge(final boolean examineOnly, final boolean silent) {
144 if (selected == null) throw new Exn.Bad("no mailbox selected");
145 for(Mailbox.Iterator it = selected.iterator(); it.next();) {
146 if (!it.deleted()) return;
147 if (!silent) star(it.uid() + " EXPUNGE");
148 if (!examineOnly) it.delete();
150 if (!silent) ok("EXPUNGE completed");
153 public void append(Mailbox m, Token t) {
154 Token[] flags = null;
156 if (t.type == t.LIST) { flags = t.l(); t = token(); }
157 if (t.type == t.QUOTED) { arrival = t.datetime(); t = token(); }
158 String literal = q();
160 Message message = new Message(null, null, new LineReader(new StringReader(literal)));
161 if (flags != null) { /* FEATURE */ }
162 selected.add(message);
163 } catch (IOException e) {
164 throw new MailException.IOException(e);
168 public void fetch(Query q, Token t) {
170 int start = -1, end = -1;
171 boolean peek = false, fast = false, all = false, full = false;
172 if (t.type == Token.LIST) tl = t.l();
173 else if (t.atom().equals("FULL")) full = true;
174 else if (t.atom().equals("ALL")) all = true;
175 else if (t.atom().equals("FAST")) fast = true;
176 // FEATURE: range requests
177 StringBuffer reply = new StringBuffer();
178 for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
179 Message m = it.cur();
180 for (int i=0; i<tl.length; i++) {
181 String s = tl[i].atom();
182 if (s.startsWith("BODY.PEEK")) { peek = true; s = "BODY" + s.substring(9); }
183 if (s.startsWith("BODY.1")) s = "BODY" + s.substring(6);
184 if (s.indexOf('<') != -1) {
185 String range = s.substring(s.indexOf('<') + 1, s.indexOf('>'));
186 s = s.substring(0, s.indexOf('<'));
187 if (range.indexOf('.') == -1) end = Integer.MAX_VALUE;
189 end = Integer.parseInt(range.substring(range.indexOf('.') + 1));
190 range = range.substring(0, range.indexOf('.'));
192 start = Integer.parseInt(range);
194 if (s.equals("ENVELOPE") || all || full) reply.append("ENVELOPE " + envelope(m) + " ");
195 if (s.equals("FLAGS") || full || all || fast) reply.append("FLAGS (" + flags(it) + ") ");
196 if (s.equals("INTERNALDATE") || full || all || fast) reply.append("INTERNALDATE "+quotify(m.arrival)+" ");
197 if (s.equals("RFC822.SIZE") || full || all || fast) reply.append("RFC822.SIZE " + m.rfc822size() + " ");
198 if (s.equals("RFC822.HEADER") || s.equals("BODY[HEADER]"))
199 { reply.append("BODY[HEADER] {" + m.allHeaders.length() + "}\r\n"); reply.append(m.allHeaders); }
200 if (s.equals("RFC822")||s.equals("RFC822.TEXT")||s.equals("BODY")||s.equals("BODY[]")||s.equals("TEXT")||full)
201 { reply.append("BODY[TEXT] {" + m.body.length() + "}\r\n"); reply.append(m.body); }
202 if (s.equals("UID")) reply.append("UID " + it.uid());
203 if (s.equals("MIME")) throw new Exn.No("FETCH BODY.MIME not supported");
204 if (s.startsWith("BODY[HEADER.FIELDS")) throw new Exn.No("partial headers not supported");
205 if (s.startsWith("BODY[HEADER.FIELDS.NOT")) throw new Exn.No("partial headers not supported");
206 if (s.equals("BODYSTRUCTURE"))
207 reply.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " +
208 m.rfc822size()+" "+ m.lines +")");
210 star(it.num() + " FETCH (" + reply.toString() + ")");
211 // FEATURE set seen flag if not BODY.PEEK
215 public void store(Query q, String what, Token[] flags) {
216 for(Mailbox.Iterator it = selected.iterator(q); it.next(); ) {
217 Message m = it.cur();
218 if (what.charAt(0) == 'F') {
219 it.deleted(false); it.seen(false); it.flagged(false); it.draft(false); it.answered(false); it.recent(false); }
220 for(int j=0; j<flags.length; j++) {
221 String flag = flags[j].flag();
222 if (flag.equals("Deleted")) it.deleted(what.charAt(0) != '-');
223 if (flag.equals("Seen")) it.seen(what.charAt(0) != '-');
224 if (flag.equals("Flagged")) it.flagged(what.charAt(0) != '-');
225 if (flag.equals("Draft")) it.draft(what.charAt(0) != '-');
226 if (flag.equals("Answered")) it.answered(what.charAt(0) != '-');
227 if (flag.equals("Recent")) it.recent( what.charAt(0) != '-');
229 selected.add(m); // re-add (?)
233 public boolean handleRequest() throws IOException {
234 LineReader lr = new LineReader(r);
235 pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
238 String s = lr.readLine();
239 if (s.indexOf(' ') == -1) { pw.println("* BAD Invalid tag"); continue; }
241 String command = atom();
242 if (command.equals("UID")) { uid = true; command = atom(); }
243 if (command.equals("AUTHENTICATE")) { login(astring(), astring()); }
244 else if (command.equals("LIST")) list(mailbox(), mailboxPattern());
245 else if (command.equals("LSUB")) lsub(mailbox(), mailboxPattern());
246 else if (command.equals("CAPABILITY")) { capability(); }
247 else if (command.equals("LOGIN")) login(astring(), astring());
248 else if (command.equals("LOGOUT")) { logout(); conn.close(); return false; }
249 else if (command.equals("RENAME")) rename(mailbox(), atom());
250 else if (command.equals("APPEND")) append(mailbox(), token());
251 else if (command.equals("EXAMINE")) select(astring(), true);
252 else if (command.equals("SELECT")) select(astring(), false);
253 else if (command.equals("COPY")) copy(Query.set(set()), mailbox());
254 else if (command.equals("DELETE")) delete(mailbox());
255 else if (command.equals("CHECK")) check();
256 else if (command.equals("CREATE")) create(astring());
257 else if (command.equals("STORE")) store(Query.set(set()), atom(), l());
258 else if (command.equals("FETCH")) fetch(Query.set(set()), token());
259 else if (command.equals("STATUS")) status(mailbox(), l());
260 else throw new Exn.Bad("unrecognized command \"" + command + "\"");
264 static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
265 static String quotify(Date d) { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
266 static String address(Address a) {return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
267 public static String addressList(Object a) {
268 if (a == null) return "NIL";
269 if (a instanceof Address) return "("+address((Address)a)+")";
270 Address[] aa = (Address[])a;
271 StringBuffer ret = new StringBuffer();
273 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
275 return ret.toString();
277 static String flags(Mailbox.Iterator it) {
279 (it.deleted() ? "\\Deleted " : "") +
280 (it.seen() ? "\\Seen " : "") +
281 (it.flagged() ? "\\Flagged " : "") +
282 (it.draft() ? "\\Draft " : "") +
283 (it.answered() ? "\\Answered " : "") +
284 (it.recent() ? "\\Recent " : "");
286 static String envelope(Message m) {
288 "(" + quotify(m.arrival.toString()) +
289 " " + quotify(m.subject) +
290 " " + addressList(m.from) +
291 " " + addressList(m.headers.get("sender")) +
292 " " + addressList(m.replyto) +
293 " " + addressList(m.to) +
294 " " + addressList(m.cc) +
295 " " + addressList(m.bcc) +
296 " " + quotify((String)m.headers.get("in-reply-to")) +
297 " " + quotify(m.messageid) +
307 if (t.type == t.LIST) throw new Exn.No("nested queries not yet supported");
308 else if (t.type == t.SET) return Query.set(t.set());
310 if (s.equals("NOT")) { not = true; continue; }
311 if (s.equals("OR")) return Query.or(query(), query());
312 if (s.equals("AND")) return Query.and(query(), query());
315 if (s.startsWith("UN")) { not = true; s = s.substring(2); }
316 if (s.equals("ANSWERED")) q = Query.flags(Flag.ANSWERED);
317 else if (s.equals("DELETED")) q = Query.flags(Flag.DELETED);
318 else if (s.equals("DRAFT")) q = Query.flags(Flag.DRAFT);
319 else if (s.equals("FLAGGED")) q = Query.flags(Flag.FLAGGED);
320 else if (s.equals("RECENT")) q = Query.flags(Flag.RECENT);
321 else if (s.equals("SEEN")) q = Query.flags(Flag.SEEN);
322 else if (s.equals("OLD")) { not = true; q = Query.flags(Flag.RECENT); }
323 else if (s.equals("NEW")) q = Query.and(Query.flags(Flag.RECENT), Query.not(Query.flags(Flag.SEEN)));
324 else if (s.equals("KEYWORD")) q = Query.header("keyword", flag());
325 else if (s.equals("HEADER")) q = Query.header(astring(), astring());
326 else if (s.equals("BCC")) q = Query.header("bcc", astring());
327 else if (s.equals("CC")) q = Query.header("cc", astring());
328 else if (s.equals("FROM")) q = Query.header("from", astring());
329 else if (s.equals("TO")) q = Query.header("to", astring());
330 else if (s.equals("SUBJECT")) q = Query.header("subject", astring());
331 else if (s.equals("LARGER")) q = Query.size(n(), Integer.MAX_VALUE);
332 else if (s.equals("SMALLER")) q = Query.size(Integer.MIN_VALUE, n());
333 else if (s.equals("BODY")) q = Query.body(astring());
334 else if (s.equals("TEXT")) q = Query.full(astring());
335 else if (s.equals("BEFORE")) q = Query.arrival(new Date(0), date());
336 else if (s.equals("SINCE")) q = Query.arrival(date(), new Date(Long.MAX_VALUE));
337 else if (s.equals("ON")) q = null; // FIXME
338 else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), date());
339 else if (s.equals("SENTSINCE")) q = Query.sent(date(), new Date(Long.MAX_VALUE));
340 else if (s.equals("SENTON")) q = null; // FIXME
341 //else if (s.equals("UID")) q = Query.uid(set());
348 private final String s;
349 private final Token[] l;
351 private static final byte NIL = 0;
352 private static final byte LIST = 1;
353 private static final byte QUOTED = 2;
354 private static final byte NUMBER = 3;
355 private static final byte ATOM = 4;
356 private static final byte BAREWORD = 5;
357 private static final byte SET = 6;
358 public Token() { n = 0; l = null; s = null; type = NIL; }
359 public Token(String quoted) { s = quoted; l = null; type = QUOTED; n = 0; }
360 public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
361 public Token(int number) { n = number; l = null; s = null; type = NUMBER; }
363 // assumes token is a flag list or a flag
364 public void setFlags(Message m) { }
365 public void addFlags(Message m) { }
366 public void deleteFlags(Message m) { }
368 public String mailboxPattern() throws Exn.Bad {
369 if (type == ATOM) return s;
370 if (type == QUOTED) return s;
371 throw new Exn.Bad("exepected a mailbox pattern");
373 public String flag() throws Exn.Bad {
374 if (type != ATOM) throw new Exn.Bad("expected a flag");
375 return s; // if first char != backslash, it is a keyword-flag
377 public int n() throws Exn.Bad {
378 if (type != NUMBER) throw new Exn.Bad("expected number");
381 public int nz() throws Exn.Bad {
382 if (type != NUMBER) throw new Exn.Bad("expected number");
383 if (n == 0) throw new Exn.Bad("expected nonzero number");
386 public String q() throws Exn.Bad {
387 if (type == NIL) return null;
388 if (type != QUOTED) throw new Exn.Bad("expected qstring");
391 public Token[] l() throws Exn.Bad {
392 if (type == NIL) return null;
393 if (type != LIST) throw new Exn.Bad("expected parenthesized list");
396 public int[] set() throws Exn.Bad {
397 if (type != ATOM) throw new Exn.Bad("expected a messageid set");
399 StringTokenizer st = new StringTokenizer(s, ",");
400 while(st.hasMoreTokens()) {
401 String s = st.nextToken();
402 if (s.indexOf(':') != -1) {
403 int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
404 String end_s = s.substring(s.indexOf(':')+1);
405 if (end_s.equals("*")) {
406 ids.addElement(new Integer(start));
407 ids.addElement(new Integer(-1));
409 int end = Integer.parseInt(end_s);
410 for(int j=start; j<=end; j++) ids.addElement(new Integer(j));
413 ids.addElement(new Integer(Integer.parseInt(s)));
416 int[] ret = new int[ids.size()];
417 for(int i=0; i<ret.length; i++) ret[i] = ((Integer)ids.elementAt(i)).intValue();
420 public Date date() throws Exn.Bad {
421 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted date");
422 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
423 } catch (ParseException p) { throw new Exn.Bad("invalid date format; " + p); }
425 public Date datetime() throws Exn.Bad {
426 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted datetime");
427 try { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").parse(s);
428 } catch (ParseException p) { throw new Exn.Bad("invalid datetime format; " + p); }
430 public String nstring() throws Exn.Bad {
431 if (type == NIL) return null;
432 if (type == QUOTED) return s;
433 throw new Exn.Bad("expected NIL or string");
435 public String astring() throws Exn.Bad {
436 if (type == ATOM) return s;
437 if (type == QUOTED) return s;
438 throw new Exn.Bad("expected atom or string");
440 public String atom() throws Exn.Bad {
441 if (type != ATOM) throw new Exn.Bad("expected atom");
442 for(int i=0; i<s.length(); i++) {
443 char c = s.charAt(i);
444 if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*')
445 throw new Exn.Bad("invalid char in atom: " + c);
449 public Mailbox mailbox() throws Exn.Bad {
450 if (type == BAREWORD && s.toLowerCase().equals("inbox")) return getMailbox("INBOX", false);
451 return getMailbox(astring(), false);
456 public char getc() throws IOException {
458 if (ret == -1) throw new EOFException();
461 public char peekc() throws IOException {
463 if (ret == -1) throw new EOFException();
467 public void fill(byte[] b) throws IOException {
469 while (num < b.length) {
470 int numread = is.read(b, num, b.length - num);
471 if (numread == -1) throw new EOFException();
476 public Token token() {
478 Vec toks = new Vec();
479 StringBuffer sb = new StringBuffer();
480 char c = getc(); while (c == ' ') c = getc();
482 while(peekc() != '}') sb.append(getc());
483 int octets = Integer.parseInt(sb.toString());
484 while(peekc() == ' ') getc(); // whitespace
485 while (getc() != '\n') { }
486 byte[] bytes = new byte[octets];
488 return new Token(new String(bytes));
489 } else if (c == '\"') {
492 if (c == '\\') sb.append(getc());
493 else if (c == '\"') break;
496 return new Token(sb.toString());
497 } else if (c == ')') {
499 } else if (c == '(') {
501 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
502 Token[] ret = new Token[toks.size()];
504 return null; // FIXME
507 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '{') break;
510 return new Token(sb.toString());
511 } catch (IOException e) {
517 public String mailboxPattern() throws Exn.Bad { return token().mailboxPattern(); }
518 public String flag() throws Exn.Bad { return token().flag(); }
519 public int n() throws Exn.Bad { return token().n(); }
520 public int nz() throws Exn.Bad { return token().nz(); }
521 public String q() throws Exn.Bad { return token().q(); }
522 public Token[] l() throws Exn.Bad { return token().l(); }
523 public int[] set() throws Exn.Bad { return token().set(); }
524 public Date date() throws Exn.Bad { return token().date(); }
525 public Date datetime() throws Exn.Bad { return token().datetime(); }
526 public String nstring() throws Exn.Bad { return token().nstring(); }
527 public String astring() throws Exn.Bad { return token().astring(); }
528 public String atom() throws Exn.Bad { return token().atom(); }
529 public Mailbox mailbox() throws Exn.Bad, IOException { return token().mailbox(); }