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(int[] set, Mailbox target) { for(int i=0; i<set.length; i++) target.add(selected.get(set[i])); }
80 public void login(String user, String password) {if (!auth(user,password))throw new Exn.No("Liar, liar, pants on fire."); }
81 public void capability() { star("CAPABILITY IMAP4rev1"); ok("Completed"); }
82 public void noop() { ok("Completed"); }
83 public void logout() { star("BYE LOGOUT received"); ok("Completed"); }
84 public void delete(Mailbox m) { if (!m.getName().toLowerCase().equals("inbox")) m.destroy(); ok("Completed"); }
85 public void subscribe(String[] args) { ok("SUBSCRIBE ignored"); }
86 public void unsubscribe(String[] args) { ok("UNSUBSCRIBE ignored"); }
87 public void check() { ok("CHECK ignored"); }
88 public void create(String mailbox){if(!mailbox.endsWith(".")&&!mailbox.equalsIgnoreCase("inbox"))getMailbox(mailbox,true);}
89 public void rename(Mailbox from, String to) {
90 if (from.getName().equalsIgnoreCase("inbox")) from.moveAllMessagesTo(getMailbox(to, true));
91 else if (to.equalsIgnoreCase("inbox")) { from.moveAllMessagesTo(getMailbox(to, true)); from.destroy(); }
95 public void status(Mailbox m, Token[] attrs) {
96 int[] list = m.list();
97 int recent = 0, unseen = 0;
98 for(int i=0; i<list.length; i++) { if (!m.seen(i)) unseen++; if (m.recent(i)) recent++; }
100 for(int i=0; i<attrs.length; i++) {
101 String s = attrs[i].atom();
102 if (s.equals("MESSAGES")) response += "MESSAGES " + list.length;
103 if (s.equals("RECENT")) response += "RECENT " + recent;
104 if (s.equals("UIDNEXT")) response += "UNSEEN " + unseen;
105 if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + m.uidvalidity;
106 if (s.equals("UNSEEN")) response += "UIDNEXT " + m.uidnext;
108 star("STATUS " + m.getName() + " (" + response + ")");
111 public void select(String mailbox, boolean examineOnly) {
112 selected = getMailbox(mailbox, false);
113 star(selected.list().length + " EXISTS");
115 int[] list = selected.list(); for(int i=0; i<list.length; i++) if (selected.recent(list[i])) recent++;
116 star(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
121 ok((examineOnly ? "EXAMINE" : "SELECT") + " completed");
124 public void close(boolean examineOnly) {
125 if (selected == null) throw new Exn.Bad("no mailbox selected");
126 expunge(false, true);
128 ok("CLOSE completed");
131 public void expunge(boolean examineOnly, boolean silent) {
132 if (selected == null) throw new Exn.Bad("no mailbox selected");
133 int[] messages = selected.list();
134 for(int i=0; i<messages.length; i++) {
135 Message m = selected.get(messages[i]);
136 if (selected.deleted(messages[i])) {
137 if (!silent) star(selected.uid(m) + " EXPUNGE");
138 if (!examineOnly) selected.delete(m);
141 if (!silent) ok("EXPUNGE completed");
144 public void append(Mailbox m, Token t) {
145 Token[] flags = null;
147 if (t.type == t.LIST) { flags = t.l(); t = token(); }
148 if (t.type == t.QUOTED) { arrival = t.datetime(); t = token(); }
149 String literal = q();
151 Message message = new Message(null, null, new LineReader(new StringReader(literal)));
152 if (flags != null) { /* FEATURE */ }
153 selected.add(message);
154 } catch (IOException e) {
155 throw new MailException.IOException(e);
159 public void fetch(int[] set, 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 // FEATURE: range requests
168 StringBuffer reply = new StringBuffer();
169 for(int j=0; j<set.length; j++) {
170 Message m = selected.get(set[j]);
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('.') == -1) end = Integer.MAX_VALUE;
180 end = Integer.parseInt(range.substring(range.indexOf('.') + 1));
181 range = range.substring(0, range.indexOf('.'));
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(selected, set[j]) + ") ");
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 " + selected.uid(set[j]));
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(set[j] + " FETCH (" + reply.toString() + ")");
202 // FEATURE set seen flag if not BODY.PEEK
206 public void store(int[] messages, String what, Token[] flags) {
207 for(int i=0; i<messages.length; i++) {
208 Message m = selected.get(messages[i]);
209 if (what.charAt(0) == 'F') {
210 selected.setDeleted(messages[i], false);
211 selected.setSeen(messages[i], false);
212 selected.setFlagged(messages[i], false);
213 selected.setDraft(messages[i], false);
214 selected.setAnswered(messages[i], false);
215 selected.setRecent(messages[i], false);
217 for(int j=0; j<flags.length; j++) {
218 String flag = flags[j].flag();
219 if (flag.equals("Deleted")) selected.setDeleted(messages[i], what.charAt(0) != '-');
220 if (flag.equals("Seen")) selected.setSeen(messages[i], what.charAt(0) != '-');
221 if (flag.equals("Flagged")) selected.setFlagged(messages[i], what.charAt(0) != '-');
222 if (flag.equals("Draft")) selected.setDraft(messages[i], what.charAt(0) != '-');
223 if (flag.equals("Answered")) selected.setAnswered(messages[i], what.charAt(0) != '-');
224 if (flag.equals("Recent")) selected.setRecent(messages[i], what.charAt(0) != '-');
226 selected.add(m); // re-add
230 public boolean handleRequest() throws IOException {
231 LineReader lr = new LineReader(r);
232 pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
235 String s = lr.readLine();
236 if (s.indexOf(' ') == -1) { pw.println("* BAD Invalid tag"); continue; }
238 String command = atom();
239 if (command.equals("UID")) { uid = true; command = atom(); }
240 if (command.equals("AUTHENTICATE")) { login(astring(), astring()); }
241 else if (command.equals("LIST")) list(mailbox(), mailboxPattern());
242 else if (command.equals("LSUB")) lsub(mailbox(), mailboxPattern());
243 else if (command.equals("CAPABILITY")) { capability(); }
244 else if (command.equals("LOGIN")) login(astring(), astring());
245 else if (command.equals("LOGOUT")) { logout(); conn.close(); return false; }
246 else if (command.equals("RENAME")) rename(mailbox(), atom());
247 else if (command.equals("APPEND")) append(mailbox(), token());
248 else if (command.equals("EXAMINE")) select(astring(), true);
249 else if (command.equals("SELECT")) select(astring(), false);
250 else if (command.equals("COPY")) copy(set(), mailbox());
251 else if (command.equals("DELETE")) delete(mailbox());
252 else if (command.equals("CHECK")) check();
253 else if (command.equals("CREATE")) create(astring());
254 else if (command.equals("STORE")) store(set(), atom(), l());
255 else if (command.equals("FETCH")) fetch(set(), token());
256 else if (command.equals("STATUS")) status(mailbox(), l());
257 else throw new Exn.Bad("unrecognized command \"" + command + "\"");
261 static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
262 static String quotify(Date d) { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
263 static String address(Address a) {return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
264 public static String addressList(Object a) {
265 if (a == null) return "NIL";
266 if (a instanceof Address) return "("+address((Address)a)+")";
267 Address[] aa = (Address[])a;
268 StringBuffer ret = new StringBuffer();
270 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
272 return ret.toString();
274 static String flags(Mailbox s, int i) {
276 (s.deleted(i) ? "\\Deleted " : "") +
277 (s.seen(i) ? "\\Seen " : "") +
278 (s.flagged(i) ? "\\Flagged " : "") +
279 (s.draft(i) ? "\\Draft " : "") +
280 (s.answered(i) ? "\\Answered " : "") +
281 (s.recent(i) ? "\\Recent " : "");
283 static String envelope(Message m) {
285 "(" + quotify(m.arrival.toString()) +
286 " " + quotify(m.subject) +
287 " " + addressList(m.from) +
288 " " + addressList(m.headers.get("sender")) +
289 " " + addressList(m.replyto) +
290 " " + addressList(m.to) +
291 " " + addressList(m.cc) +
292 " " + addressList(m.bcc) +
293 " " + quotify((String)m.headers.get("in-reply-to")) +
294 " " + quotify(m.messageid) +
304 if (t.type == t.LIST) throw new Exn.No("nested queries not yet supported");
305 else if (t.type == t.SET) return Query.set(t.set());
307 if (s.equals("NOT")) { not = true; continue; }
308 if (s.equals("OR")) return Query.or(query(), query());
309 if (s.equals("AND")) return Query.and(query(), query());
312 if (s.startsWith("UN")) { not = true; s = s.substring(2); }
313 if (s.equals("ANSWERED")) q = Query.Flag.ANSWERED;
314 else if (s.equals("DELETED")) q = Query.Flag.DELETED;
315 else if (s.equals("DRAFT")) q = Query.Flag.DRAFT;
316 else if (s.equals("FLAGGED")) q = Query.Flag.FLAGGED;
317 else if (s.equals("RECENT")) q = Query.Flag.RECENT;
318 else if (s.equals("SEEN")) q = Query.Flag.SEEN;
319 else if (s.equals("OLD")) { not = true; q = Query.Flag.RECENT; }
320 else if (s.equals("NEW")) q = Query.and(Query.Flag.RECENT, Query.not(Query.Flag.SEEN));
321 else if (s.equals("KEYWORD")) q = Query.header("keyword", flag());
322 else if (s.equals("HEADER")) q = Query.header(astring(), astring());
323 else if (s.equals("BCC")) q = Query.header("bcc", astring());
324 else if (s.equals("CC")) q = Query.header("cc", astring());
325 else if (s.equals("FROM")) q = Query.header("from", astring());
326 else if (s.equals("TO")) q = Query.header("to", astring());
327 else if (s.equals("SUBJECT")) q = Query.header("subject", astring());
328 else if (s.equals("LARGER")) q = Query.size(n(), true);
329 else if (s.equals("SMALLER")) q = Query.size(n(), false);
330 else if (s.equals("BODY")) q = Query.fullText(astring(), true, false);
331 else if (s.equals("TEXT")) q = Query.fullText(astring(), true, true);
332 else if (s.equals("BEFORE")) q = Query.arrival(date(), true, false);
333 else if (s.equals("SINCE")) q = Query.arrival(date(), false, true);
334 else if (s.equals("ON")) q = Query.arrival(date(), true, true);
335 else if (s.equals("SENTBEFORE")) q = Query.sent(date(), true, false);
336 else if (s.equals("SENTSINCE")) q = Query.sent(date(), false, true);
337 else if (s.equals("SENTON")) q = Query.sent(date(), true, true);
338 else if (s.equals("UID")) q = Query.uid(set());
344 private final String s;
345 private final Token[] l;
347 private static final byte NIL = 0;
348 private static final byte LIST = 1;
349 private static final byte QUOTED = 2;
350 private static final byte NUMBER = 3;
351 private static final byte ATOM = 4;
352 private static final byte BAREWORD = 5;
353 private static final byte SET = 6;
354 public Token() { n = 0; l = null; s = null; type = NIL; }
355 public Token(String quoted) { s = quoted; l = null; type = QUOTED; n = 0; }
356 public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
357 public Token(int number) { n = number; l = null; s = null; type = NUMBER; }
359 // assumes token is a flag list or a flag
360 public void setFlags(Message m) { }
361 public void addFlags(Message m) { }
362 public void deleteFlags(Message m) { }
364 public String mailboxPattern() throws Exn.Bad {
365 if (type == ATOM) return s;
366 if (type == QUOTED) return s;
367 throw new Exn.Bad("exepected a mailbox pattern");
369 public String flag() throws Exn.Bad {
370 if (type != ATOM) throw new Exn.Bad("expected a flag");
371 return s; // if first char != backslash, it is a keyword-flag
373 public int n() throws Exn.Bad {
374 if (type != NUMBER) throw new Exn.Bad("expected number");
377 public int nz() throws Exn.Bad {
378 if (type != NUMBER) throw new Exn.Bad("expected number");
379 if (n == 0) throw new Exn.Bad("expected nonzero number");
382 public String q() throws Exn.Bad {
383 if (type == NIL) return null;
384 if (type != QUOTED) throw new Exn.Bad("expected qstring");
387 public Token[] l() throws Exn.Bad {
388 if (type == NIL) return null;
389 if (type != LIST) throw new Exn.Bad("expected parenthesized list");
392 public int[] set() throws Exn.Bad {
393 if (type != ATOM) throw new Exn.Bad("expected a messageid set");
395 StringTokenizer st = new StringTokenizer(s, ",");
396 while(st.hasMoreTokens()) {
397 String s = st.nextToken();
398 if (s.indexOf(':') != -1) {
399 int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
400 String end_s = s.substring(s.indexOf(':')+1);
401 if (end_s.equals("*")) {
402 ids.addElement(new Integer(start));
403 ids.addElement(new Integer(-1));
405 int end = Integer.parseInt(end_s);
406 for(int j=start; j<=end; j++) ids.addElement(new Integer(j));
409 ids.addElement(new Integer(Integer.parseInt(s)));
412 int[] ret = new int[ids.size()];
413 for(int i=0; i<ret.length; i++) ret[i] = ((Integer)ids.elementAt(i)).intValue();
416 public Date date() throws Exn.Bad {
417 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted date");
418 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
419 } catch (ParseException p) { throw new Exn.Bad("invalid date format; " + p); }
421 public Date datetime() throws Exn.Bad {
422 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted datetime");
423 try { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").parse(s);
424 } catch (ParseException p) { throw new Exn.Bad("invalid datetime format; " + p); }
426 public String nstring() throws Exn.Bad {
427 if (type == NIL) return null;
428 if (type == QUOTED) return s;
429 throw new Exn.Bad("expected NIL or string");
431 public String astring() throws Exn.Bad {
432 if (type == ATOM) return s;
433 if (type == QUOTED) return s;
434 throw new Exn.Bad("expected atom or string");
436 public String atom() throws Exn.Bad {
437 if (type != ATOM) throw new Exn.Bad("expected atom");
438 for(int i=0; i<s.length(); i++) {
439 char c = s.charAt(i);
440 if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*')
441 throw new Exn.Bad("invalid char in atom: " + c);
445 public Mailbox mailbox() throws Exn.Bad {
446 if (type == BAREWORD && s.toLowerCase().equals("inbox")) return getMailbox("INBOX", false);
447 return getMailbox(astring(), false);
452 public char getc() throws IOException {
454 if (ret == -1) throw new EOFException();
457 public char peekc() throws IOException {
459 if (ret == -1) throw new EOFException();
463 public void fill(byte[] b) throws IOException {
465 while (num < b.length) {
466 int numread = is.read(b, num, b.length - num);
467 if (numread == -1) throw new EOFException();
472 public Token token() {
474 Vec toks = new Vec();
475 StringBuffer sb = new StringBuffer();
476 char c = getc(); while (c == ' ') c = getc();
478 while(peekc() != '}') sb.append(getc());
479 int octets = Integer.parseInt(sb.toString());
480 while(peekc() == ' ') getc(); // whitespace
481 while (getc() != '\n') { }
482 byte[] bytes = new byte[octets];
484 return new Token(new String(bytes));
485 } else if (c == '\"') {
488 if (c == '\\') sb.append(getc());
489 else if (c == '\"') break;
492 return new Token(sb.toString());
493 } else if (c == ')') {
495 } else if (c == '(') {
497 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
498 Token[] ret = new Token[toks.size()];
500 return null; // FIXME
503 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '{') break;
506 return new Token(sb.toString());
507 } catch (IOException e) {
513 public String mailboxPattern() throws Exn.Bad { return token().mailboxPattern(); }
514 public String flag() throws Exn.Bad { return token().flag(); }
515 public int n() throws Exn.Bad { return token().n(); }
516 public int nz() throws Exn.Bad { return token().nz(); }
517 public String q() throws Exn.Bad { return token().q(); }
518 public Token[] l() throws Exn.Bad { return token().l(); }
519 public int[] set() throws Exn.Bad { return token().set(); }
520 public Date date() throws Exn.Bad { return token().date(); }
521 public Date datetime() throws Exn.Bad { return token().datetime(); }
522 public String nstring() throws Exn.Bad { return token().nstring(); }
523 public String astring() throws Exn.Bad { return token().astring(); }
524 public String atom() throws Exn.Bad { return token().atom(); }
525 public Mailbox mailbox() throws Exn.Bad, IOException { return token().mailbox(); }