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++) {
99 Message message = m.get(list[i]);
100 if (!message.seen) unseen++;
101 if (message.recent) recent++;
103 String response = "";
104 for(int i=0; i<attrs.length; i++) {
105 String s = attrs[i].atom();
106 if (s.equals("MESSAGES")) response += "MESSAGES " + list.length;
107 if (s.equals("RECENT")) response += "RECENT " + recent;
108 if (s.equals("UIDNEXT")) response += "UNSEEN " + unseen;
109 if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + m.uidvalidity;
110 if (s.equals("UNSEEN")) response += "UIDNEXT " + m.uidnext;
112 star("STATUS " + m.getName() + " (" + response + ")");
115 public void select(String mailbox, boolean examineOnly) {
116 selected = getMailbox(mailbox, false);
117 star(selected.list().length + " EXISTS");
119 int[] list = selected.list(); for(int i=0; i<list.length; i++) if (selected.get(list[i]).recent) recent++;
120 star(recent + " RECENT");
121 //star("OK [UNSEEN 12] Message 12 is first unseen"); FEATURE
122 star("OK [UIDVALIDITY " + selected.uidvalidity + "] UIDs valid");
123 star("FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
124 // FEATURE: READ-WRITE / READ-ONLY
125 ok((examineOnly ? "EXAMINE" : "SELECT") + " completed");
128 public void close(boolean examineOnly) {
129 if (selected == null) throw new Exn.Bad("no mailbox selected");
130 expunge(false, true);
132 ok("CLOSE completed");
135 public void expunge(boolean examineOnly, boolean silent) {
136 if (selected == null) throw new Exn.Bad("no mailbox selected");
137 int[] messages = selected.list();
138 for(int i=0; i<messages.length; i++) {
139 Message m = selected.get(messages[i]);
141 if (!silent) star(m.uid + " EXPUNGE");
142 if (!examineOnly) selected.delete(m);
145 if (!silent) ok("EXPUNGE completed");
148 public void append(Mailbox m, Token t) {
149 Token[] flags = null;
151 if (t.type == t.LIST) { flags = t.l(); t = token(); }
152 if (t.type == t.QUOTED) { arrival = t.datetime(); t = token(); }
153 String literal = q();
155 Message message = new Message(null, null, new LineReader(new StringReader(literal)));
156 if (flags != null) { /* FEATURE */ }
157 selected.add(message);
158 } catch (IOException e) {
159 throw new MailException.IOException(e);
163 public void fetch(int[] set, Token t) {
165 int start = -1, end = -1;
166 boolean peek = false, fast = false, all = false, full = false;
167 if (t.type == Token.LIST) tl = t.l();
168 else if (t.atom().equals("FULL")) full = true;
169 else if (t.atom().equals("ALL")) all = true;
170 else if (t.atom().equals("FAST")) fast = true;
171 // FEATURE: range requests
172 StringBuffer reply = new StringBuffer();
173 for(int j=0; j<set.length; j++) {
174 Message m = selected.get(set[j]);
175 for (int i=0; i<tl.length; i++) {
176 String s = tl[i].atom();
177 if (s.startsWith("BODY.PEEK")) { peek = true; s = "BODY" + s.substring(9); }
178 if (s.startsWith("BODY.1")) s = "BODY" + s.substring(6);
179 if (s.indexOf('<') != -1) {
180 String range = s.substring(s.indexOf('<') + 1, s.indexOf('>'));
181 s = s.substring(0, s.indexOf('<'));
182 if (range.indexOf('.') == -1) end = Integer.MAX_VALUE;
184 end = Integer.parseInt(range.substring(range.indexOf('.') + 1));
185 range = range.substring(0, range.indexOf('.'));
187 start = Integer.parseInt(range);
189 if (s.equals("ENVELOPE") || all || full) reply.append("ENVELOPE " + envelope(m) + " ");
190 if (s.equals("FLAGS") || full || all || fast) reply.append("FLAGS (" + flags(m) + ") ");
191 if (s.equals("INTERNALDATE") || full || all || fast) reply.append("INTERNALDATE "+quotify(m.arrival)+" ");
192 if (s.equals("RFC822.SIZE") || full || all || fast) reply.append("RFC822.SIZE " + m.rfc822size() + " ");
193 if (s.equals("RFC822.HEADER") || s.equals("BODY[HEADER]"))
194 { reply.append("BODY[HEADER] {" + m.allHeaders.length() + "}\r\n"); reply.append(m.allHeaders); }
195 if (s.equals("RFC822")||s.equals("RFC822.TEXT")||s.equals("BODY")||s.equals("BODY[]")||s.equals("TEXT")||full)
196 { reply.append("BODY[TEXT] {" + m.body.length() + "}\r\n"); reply.append(m.body); }
197 if (s.equals("UID")) reply.append("UID " + m.uid);
198 if (s.equals("MIME")) throw new Exn.No("FETCH BODY.MIME not supported");
199 if (s.startsWith("BODY[HEADER.FIELDS")) throw new Exn.No("partial headers not supported");
200 if (s.startsWith("BODY[HEADER.FIELDS.NOT")) throw new Exn.No("partial headers not supported");
201 if (s.equals("BODYSTRUCTURE"))
202 reply.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " +
203 m.rfc822size()+" "+ m.numLines() +")");
205 star(m.messageNum + " FETCH (" + reply.toString() + ")");
206 // FEATURE set seen flag if not BODY.PEEK
210 public void store(int[] messages, String what, Token[] flags) {
211 for(int i=0; i<messages.length; i++) {
212 Message m = selected.get(messages[i]);
213 if (what.charAt(0) == 'F') m.deleted = m.seen = m.flagged = m.draft = m.answered = m.recent = false;
214 for(int j=0; j<flags.length; j++) {
215 String flag = flags[j].flag();
216 if (flag.equals("Deleted")) m.deleted = what.charAt(0) != '-';
217 if (flag.equals("Seen")) m.seen = what.charAt(0) != '-';
218 if (flag.equals("Flagged")) m.flagged = what.charAt(0) != '-';
219 if (flag.equals("Draft")) m.draft = what.charAt(0) != '-';
220 if (flag.equals("Answered")) m.answered = what.charAt(0) != '-';
221 if (flag.equals("Recent")) m.recent = what.charAt(0) != '-';
223 selected.add(m); // re-add
227 public boolean handleRequest() throws IOException {
228 LineReader lr = new LineReader(r);
229 pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
232 String s = lr.readLine();
233 if (s.indexOf(' ') == -1) { pw.println("* BAD Invalid tag"); continue; }
235 String command = atom();
236 if (command.equals("UID")) { uid = true; command = atom(); }
237 if (command.equals("AUTHENTICATE")) { login(astring(), astring()); }
238 else if (command.equals("LIST")) list(mailbox(), mailboxPattern());
239 else if (command.equals("LSUB")) lsub(mailbox(), mailboxPattern());
240 else if (command.equals("CAPABILITY")) { capability(); }
241 else if (command.equals("LOGIN")) login(astring(), astring());
242 else if (command.equals("LOGOUT")) { logout(); conn.close(); return false; }
243 else if (command.equals("RENAME")) rename(mailbox(), atom());
244 else if (command.equals("APPEND")) append(mailbox(), token());
245 else if (command.equals("EXAMINE")) select(astring(), true);
246 else if (command.equals("SELECT")) select(astring(), false);
247 else if (command.equals("COPY")) copy(set(), mailbox());
248 else if (command.equals("DELETE")) delete(mailbox());
249 else if (command.equals("CHECK")) check();
250 else if (command.equals("CREATE")) create(astring());
251 else if (command.equals("STORE")) store(set(), atom(), l());
252 else if (command.equals("FETCH")) fetch(set(), token());
253 else if (command.equals("STATUS")) status(mailbox(), l());
254 else throw new Exn.Bad("unrecognized command \"" + command + "\"");
258 static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
259 static String quotify(Date d) { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
260 static String address(Address a) {return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
261 public static String addressList(Object a) {
262 if (a == null) return "NIL";
263 if (a instanceof Address) return "("+address((Address)a)+")";
264 Address[] aa = (Address[])a;
265 StringBuffer ret = new StringBuffer();
267 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
269 return ret.toString();
271 static String flags(Message m) {
273 (m.deleted ? "\\Deleted " : "") +
274 (m.seen ? "\\Seen " : "") +
275 (m.flagged ? "\\Flagged " : "") +
276 (m.draft ? "\\Draft " : "") +
277 (m.answered ? "\\Answered " : "") +
278 (m.recent ? "\\Recent " : "");
280 static String envelope(Message m) {
282 "(" + quotify(m.arrival.toString()) +
283 " " + quotify(m.subject) +
284 " " + addressList(m.from) +
285 " " + addressList(m.headers.get("sender")) +
286 " " + addressList(m.replyto) +
287 " " + addressList(m.to) +
288 " " + addressList(m.cc) +
289 " " + addressList(m.bcc) +
290 " " + quotify((String)m.headers.get("in-reply-to")) +
291 " " + quotify(m.messageid) +
301 if (t.type == t.LIST) throw new Exn.No("nested queries not yet supported");
302 else if (t.type == t.SET) return Query.set(t.set());
304 if (s.equals("NOT")) { not = true; continue; }
305 if (s.equals("OR")) return Query.or(query(), query());
306 if (s.equals("AND")) return Query.and(query(), query());
309 if (s.startsWith("UN")) { not = true; s = s.substring(2); }
310 if (s.equals("ANSWERED")) q = Query.Flag.ANSWERED;
311 else if (s.equals("DELETED")) q = Query.Flag.DELETED;
312 else if (s.equals("DRAFT")) q = Query.Flag.DRAFT;
313 else if (s.equals("FLAGGED")) q = Query.Flag.FLAGGED;
314 else if (s.equals("RECENT")) q = Query.Flag.RECENT;
315 else if (s.equals("SEEN")) q = Query.Flag.SEEN;
316 else if (s.equals("OLD")) { not = true; q = Query.Flag.RECENT; }
317 else if (s.equals("NEW")) q = Query.and(Query.Flag.RECENT, Query.not(Query.Flag.SEEN));
318 else if (s.equals("KEYWORD")) q = Query.header("keyword", flag());
319 else if (s.equals("HEADER")) q = Query.header(astring(), astring());
320 else if (s.equals("BCC")) q = Query.header("bcc", astring());
321 else if (s.equals("CC")) q = Query.header("cc", astring());
322 else if (s.equals("FROM")) q = Query.header("from", astring());
323 else if (s.equals("TO")) q = Query.header("to", astring());
324 else if (s.equals("SUBJECT")) q = Query.header("subject", astring());
325 else if (s.equals("LARGER")) q = Query.size(n(), true);
326 else if (s.equals("SMALLER")) q = Query.size(n(), false);
327 else if (s.equals("BODY")) q = Query.fullText(astring(), true, false);
328 else if (s.equals("TEXT")) q = Query.fullText(astring(), true, true);
329 else if (s.equals("BEFORE")) q = Query.arrival(date(), true, false);
330 else if (s.equals("SINCE")) q = Query.arrival(date(), false, true);
331 else if (s.equals("ON")) q = Query.arrival(date(), true, true);
332 else if (s.equals("SENTBEFORE")) q = Query.sent(date(), true, false);
333 else if (s.equals("SENTSINCE")) q = Query.sent(date(), false, true);
334 else if (s.equals("SENTON")) q = Query.sent(date(), true, true);
335 else if (s.equals("UID")) q = Query.uid(set());
341 private final String s;
342 private final Token[] l;
344 private static final byte NIL = 0;
345 private static final byte LIST = 1;
346 private static final byte QUOTED = 2;
347 private static final byte NUMBER = 3;
348 private static final byte ATOM = 4;
349 private static final byte BAREWORD = 5;
350 private static final byte SET = 6;
351 public Token() { n = 0; l = null; s = null; type = NIL; }
352 public Token(String quoted) { s = quoted; l = null; type = QUOTED; n = 0; }
353 public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
354 public Token(int number) { n = number; l = null; s = null; type = NUMBER; }
356 // assumes token is a flag list or a flag
357 public void setFlags(Message m) { }
358 public void addFlags(Message m) { }
359 public void deleteFlags(Message m) { }
361 public String mailboxPattern() throws Exn.Bad {
362 if (type == ATOM) return s;
363 if (type == QUOTED) return s;
364 throw new Exn.Bad("exepected a mailbox pattern");
366 public String flag() throws Exn.Bad {
367 if (type != ATOM) throw new Exn.Bad("expected a flag");
368 return s; // if first char != backslash, it is a keyword-flag
370 public int n() throws Exn.Bad {
371 if (type != NUMBER) throw new Exn.Bad("expected number");
374 public int nz() throws Exn.Bad {
375 if (type != NUMBER) throw new Exn.Bad("expected number");
376 if (n == 0) throw new Exn.Bad("expected nonzero number");
379 public String q() throws Exn.Bad {
380 if (type == NIL) return null;
381 if (type != QUOTED) throw new Exn.Bad("expected qstring");
384 public Token[] l() throws Exn.Bad {
385 if (type == NIL) return null;
386 if (type != LIST) throw new Exn.Bad("expected parenthesized list");
389 public int[] set() throws Exn.Bad {
390 if (type != ATOM) throw new Exn.Bad("expected a messageid set");
392 StringTokenizer st = new StringTokenizer(s, ",");
393 while(st.hasMoreTokens()) {
394 String s = st.nextToken();
395 if (s.indexOf(':') != -1) {
396 int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
397 String end_s = s.substring(s.indexOf(':')+1);
398 if (end_s.equals("*")) {
399 ids.addElement(new Integer(start));
400 ids.addElement(new Integer(-1));
402 int end = Integer.parseInt(end_s);
403 for(int j=start; j<=end; j++) ids.addElement(new Integer(j));
406 ids.addElement(new Integer(Integer.parseInt(s)));
409 int[] ret = new int[ids.size()];
410 for(int i=0; i<ret.length; i++) ret[i] = ((Integer)ids.elementAt(i)).intValue();
413 public Date date() throws Exn.Bad {
414 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted date");
415 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
416 } catch (ParseException p) { throw new Exn.Bad("invalid date format; " + p); }
418 public Date datetime() throws Exn.Bad {
419 if (type != QUOTED && type != ATOM) throw new Exn.Bad("Expected quoted or unquoted datetime");
420 try { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").parse(s);
421 } catch (ParseException p) { throw new Exn.Bad("invalid datetime format; " + p); }
423 public String nstring() throws Exn.Bad {
424 if (type == NIL) return null;
425 if (type == QUOTED) return s;
426 throw new Exn.Bad("expected NIL or string");
428 public String astring() throws Exn.Bad {
429 if (type == ATOM) return s;
430 if (type == QUOTED) return s;
431 throw new Exn.Bad("expected atom or string");
433 public String atom() throws Exn.Bad {
434 if (type != ATOM) throw new Exn.Bad("expected atom");
435 for(int i=0; i<s.length(); i++) {
436 char c = s.charAt(i);
437 if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*')
438 throw new Exn.Bad("invalid char in atom: " + c);
442 public Mailbox mailbox() throws Exn.Bad {
443 if (type == BAREWORD && s.toLowerCase().equals("inbox")) return getMailbox("INBOX", false);
444 return getMailbox(astring(), false);
449 public char getc() throws IOException {
451 if (ret == -1) throw new EOFException();
454 public char peekc() throws IOException {
456 if (ret == -1) throw new EOFException();
460 public void fill(byte[] b) throws IOException {
462 while (num < b.length) {
463 int numread = is.read(b, num, b.length - num);
464 if (numread == -1) throw new EOFException();
469 public Token token() {
471 Vec toks = new Vec();
472 StringBuffer sb = new StringBuffer();
473 char c = getc(); while (c == ' ') c = getc();
475 while(peekc() != '}') sb.append(getc());
476 int octets = Integer.parseInt(sb.toString());
477 while(peekc() == ' ') getc(); // whitespace
478 while (getc() != '\n') { }
479 byte[] bytes = new byte[octets];
481 return new Token(new String(bytes));
482 } else if (c == '\"') {
485 if (c == '\\') sb.append(getc());
486 else if (c == '\"') break;
489 return new Token(sb.toString());
490 } else if (c == ')') {
492 } else if (c == '(') {
494 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
495 Token[] ret = new Token[toks.size()];
497 return null; // FIXME
500 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '{') break;
503 return new Token(sb.toString());
504 } catch (IOException e) {
510 public String mailboxPattern() throws Exn.Bad { return token().mailboxPattern(); }
511 public String flag() throws Exn.Bad { return token().flag(); }
512 public int n() throws Exn.Bad { return token().n(); }
513 public int nz() throws Exn.Bad { return token().nz(); }
514 public String q() throws Exn.Bad { return token().q(); }
515 public Token[] l() throws Exn.Bad { return token().l(); }
516 public int[] set() throws Exn.Bad { return token().set(); }
517 public Date date() throws Exn.Bad { return token().date(); }
518 public Date datetime() throws Exn.Bad { return token().datetime(); }
519 public String nstring() throws Exn.Bad { return token().nstring(); }
520 public String astring() throws Exn.Bad { return token().astring(); }
521 public String atom() throws Exn.Bad { return token().atom(); }
522 public Mailbox mailbox() throws Exn.Bad, IOException { return token().mailbox(); }