1 package org.ibex.mail.protocol;
2 import org.ibex.mail.*;
3 import org.ibex.util.*;
4 import org.ibex.mail.target.*;
10 // FIXME: tagged responses
12 // FEATURE: pipelining
13 // FEATURE: support [charset]
14 public class IMAP extends MessageProtocol {
16 public static void main(String[] args) throws Exception {
17 ServerSocket ss = new ServerSocket(143);
19 System.out.println("listening");
20 final Socket s = ss.accept();
21 System.out.println("connected");
26 } catch (Exception e) {
34 public static class IMAPException extends MailException { public IMAPException(String s) { super(s); } }
35 public static class No extends IMAPException { public No(String s) { super(s); } }
36 public static class Bad extends IMAPException { public Bad(String s) { super(s); } }
38 public static void service(Socket s) { /* FIXME */ }
40 private static class Listener extends Incoming {
41 private InputStream is;
42 private PushbackReader r;
47 Mailbox selected = null;
53 public void init() { }
54 public Listener(Socket conn, String vhost) { this.vhost = vhost; this.conn = conn; this.selected = null; }
56 private void ok(String s) { star("OK " + s); }
57 private void star(String s) { pw.println("* " + s); }
58 private boolean auth(String user, String pass) { /* FEATURE */ return user.equals("megacz") && pass.equals(""); }
59 private Mailbox getMailbox(String name, boolean create) {
61 while(name.length() > 0) {
62 int end = name.length();
63 if (name.indexOf('.') != -1) end = name.indexOf('.');
64 m = m.slash(name.substring(0, end), create);
65 name = name.substring(end);
70 // sharing problem? immutability helps
71 public void copy(int[] set, Mailbox target) {
72 for(int i=0; i<set.length; i++) target.add(selected.get(set[i]));
76 public void login(String user, String password) { if (!auth(user, password)) throw new No("Liar, liar, pants on fire."); }
77 public void capability() { star("CAPABILITY IMAP4rev1"); ok("Completed"); }
78 public void noop() { ok("Completed"); }
79 public void logout() { star("BYE LOGOUT received"); ok("Completed"); }
80 public void delete(Mailbox m) { if (!m.getName().toLowerCase().equals("inbox")) m.destroy(); }
81 public void subscribe(String[] args) { ok("SUBSCRIBE ignored"); }
82 public void unsubscribe(String[] args) { ok("UNSUBSCRIBE ignored"); }
83 public void check(String[] args, boolean examineOnly) { ok("check complete"); }
84 public void lsub(Mailbox m, String s) { list(m, s); }
85 public void list(Mailbox m, String s) { star("LIST () \".\" INBOX"); ok("LIST completed"); } // FIXME
86 public void create(String mailbox){if(!mailbox.endsWith(".")&&!mailbox.equalsIgnoreCase("inbox"))getMailbox(mailbox,true);}
87 public void rename(Mailbox from, String to) {
88 if (from.getName().toLowerCase().equals("inbox")) from.moveAllMessagesTo(getMailbox(to, true));
89 else if (to.toLowerCase().equals("inbox")) { from.moveAllMessagesTo(getMailbox(to, true)); from.destroy(); }
93 public void status(Mailbox m, Token[] attrs) {
94 boolean messages = false, recent = false, uidnext = false, uidvalidity = false, unseen = false;
95 for(int i=0; i<attrs.length; i++) {
96 String s = attrs[i].atom();
97 if (s.equals("MESSAGES")) messages = true;
98 if (s.equals("RECENT")) recent = true;
99 if (s.equals("UIDNEXT")) uidnext = true;
100 if (s.equals("UIDVALIDITY")) uidvalidity = true;
101 if (s.equals("UNSEEN")) unseen = true;
103 int[] list = m.list(); int numRecent = 0, numUnseen = 0;
104 for(int i=0; i<list.length; i++) {
105 Message message = m.get(list[i]);
106 if (!message.seen) numUnseen++;
107 if (message.recent) numRecent++;
109 star("STATUS FIXME ( " +
110 (messages ? ("MESSAGES " + list.length + " ") : "") +
111 (recent ? ("RECENT " + numRecent + " ") : "") +
112 (unseen ? ("UNSEEN " + numUnseen + " ") : "") +
113 (uidvalidity ? ("UIDVALIDITY " + m.uidvalidity + " ") : "") +
114 (uidnext ? ("UIDNEXT " + m.uidnext + " ") : "") + ")");
117 public void select(String[] args, boolean examineOnly) {
118 if (args.length < 1) throw new Bad("Not enough arguments");
119 selected = getMailbox(args[0], false);
120 if (selected == null) throw new No("No such mailbox");
121 star(selected.list().length + " EXISTS");
123 //star("OK [UNSEEN 12] Message 12 is first unseen"); FEATURE
124 star("OK [UIDVALIDITY " + selected.uidvalidity + "] UIDs valid");
125 star("FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
126 ok(/* FEATURE: READ-WRITE / READ-ONLY */ (examineOnly ? "EXAMINE" : "SELECT") + " completed");
129 public void close(String[] args, boolean examineOnly) {
130 if (selected == null) throw new Bad("no mailbox selected");
131 expunge(new String[] { }, false, true);
133 ok("CLOSE completed");
136 public void expunge(String[] args, boolean examineOnly, boolean silent) {
137 if (selected == null) throw new Bad("no mailbox selected");
138 int[] messages = selected.list();
139 for(int i=0; i<messages.length; i++) {
140 Message m = selected.get(messages[i]);
142 if (!silent) star(m.uid + " EXPUNGE");
143 if (!examineOnly) selected.delete(m);
146 if (!silent) ok("EXPUNGE completed");
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();
156 Message message = new Message(null, null, new LineReader(new StringReader(literal)));
157 if (flags != null) setFlags(flags, message);
158 //if (arrival != null) message.arrival = arrival; FIXME
159 selected.add(message);
160 } catch (IOException e) {
165 public void setFlags(Token[] t, Message m) { /* FIXME */ }
168 public void fetch(int[] set, Token t) {
170 int start = -1, end = -1;
171 boolean peek = false;
172 if (t.type == Token.LIST) tl = t.l();
173 else if (t.atom().equals("FULL")) tl = (Token[]) parse("FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY");
174 else if (t.atom().equals("ALL")) tl = (Token[]) parse("FLAGS INTERNALDATE RFC822.SIZE ENVELOPE");
175 else if (t.atom().equals("FAST")) tl = (Token[]) parse("FLAGS INTERNALDATE RFC822.SIZE");
176 // FEATURE: range requests
177 StringBuffer reply = new StringBuffer();
178 Message m = null; // FIXME
179 for (int i=0; i<tl.length; i++) {
180 String s = tl[i].atom();
181 if (s.startsWith("BODY.PEEK")) { peek = true; s = "BODY" + s.substring(9); }
182 if (s.startsWith("BODY.1")) s = "BODY" + s.substring(6);
183 if (s.indexOf('<') != -1) {
184 String range = s.substring(s.indexOf('<') + 1, s.indexOf('>'));
185 s = s.substring(0, s.indexOf('<'));
186 if (range.indexOf('.') == -1) end = Integer.MAX_VALUE;
188 end = Integer.parseInt(range.substring(range.indexOf('.') + 1));
189 range = range.substring(0, range.indexOf('.'));
191 start = Integer.parseInt(range);
193 if (s.equals("ENVELOPE")) reply.append("ENVELOPE " + envelope(m) + " ");
194 else if (s.equals("FLAGS")) reply.append("FLAGS (" + flags(m) + ") ");
195 else if (s.equals("INTERNALDATE")) reply.append("INTERNALDATE " + quotify(m.arrival) + " ");
196 else if (s.equals("RFC822.SIZE")) reply.append("RFC822.SIZE " + m.rfc822size() + " ");
197 else if (s.equals("RFC822.HEADER") || s.equals("BODY[HEADER]"))
198 { reply.append("BODY[HEADER] {" + m.allHeaders.length() + "}\r\n"); reply.append(m.allHeaders); }
199 else if (s.equals("RFC822")||s.equals("RFC822.TEXT")||s.equals("BODY") || s.equals("BODY[]") || s.equals("TEXT"))
200 { reply.append("BODY[TEXT] {" + m.body.length() + "}\r\n"); reply.append(m.body); }
201 else if (s.equals("UID")) reply.append("UID " + m.uid);
202 else if (s.equals("MIME")) throw new No("FETCH BODY.MIME not supported");
203 else if (s.startsWith("BODY[HEADER.FIELDS")) throw new No("partial headers not supported");
204 else if (s.startsWith("BODY[HEADER.FIELDS.NOT")) throw new No("partial headers not supported");
205 else if (s.equals("BODYSTRUCTURE"))
206 reply.append("(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " +
207 m.rfc822size()+" "+ m.numLines() +")");
208 else if (s.startsWith("BODY")) throw new No("FETCH BODY[*] not supported");
209 else throw new Bad("unrecognized FETCH argument \"" + s + "\"");
211 star(m.messageNum + " FETCH (" + reply.toString() + ")");
212 // FEATURE set seen flag if not BODY.PEEK
215 public void store(int[] messages, String what, Token[] flags) {
216 for(int i=0; i<messages.length; i++) {
217 Message m = selected.get(messages[i]);
218 if (what.charAt(0) == 'F') m.deleted = m.seen = m.flagged = m.draft = m.answered = m.recent = false;
219 for(int j=0; j<flags.length; j++) {
220 String flag = flags[j].flag();
221 if (flag.equals("Deleted")) m.deleted = what.charAt(0) != '-';
222 if (flag.equals("Seen")) m.seen = what.charAt(0) != '-';
223 if (flag.equals("Flagged")) m.flagged = what.charAt(0) != '-';
224 if (flag.equals("Draft")) m.draft = what.charAt(0) != '-';
225 if (flag.equals("Answered")) m.answered = what.charAt(0) != '-';
226 if (flag.equals("Recent")) m.recent = what.charAt(0) != '-';
228 selected.add(m); // re-add
232 public boolean handleRequest(LineReader r, PrintWriter pw) throws IOException {
233 pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
236 String s = r.readLine();
237 if (s.indexOf(' ') == -1) { pw.println("* BAD Invalid tag"); continue; }
239 String command = atom();
240 if (command.equals("UID")) { uid = true; command = atom(); }
241 if (command.equals("AUTHENTICATE")) { login(astring(), astring()); }
242 else if (command.equals("LIST")) list(mailbox(), mailboxPattern());
243 else if (command.equals("LSUB")) lsub(mailbox(), mailboxPattern());
244 else if (command.equals("CAPABILITY")) { capability(); }
245 else if (command.equals("LOGIN")) login(astring(), astring());
246 else if (command.equals("LOGOUT")) { logout(); conn.close(); return false; }
247 else if (command.equals("RENAME")) rename(mailbox(), atom());
248 else if (command.equals("APPEND")) append(mailbox(), token());
249 //else if (command.equals("EXAMINE")) examine(mailbox()); FIXME
250 else if (command.equals("COPY")) copy(set(), mailbox());
251 else if (command.equals("DELETE")) delete(mailbox());
252 //else if (command.equals("CREATE")) create(mailbox()); FIXME
253 else if (command.equals("STORE")) store(set(), atom(), l());
254 else if (command.equals("FETCH")) fetch(set(), token());
255 else if (command.equals("STATUS")) status(mailbox(), l());
256 else throw new Bad("unrecognized command \"" + command + "\"");
260 static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
261 static String quotify(Date d) { throw new Error("not implemented"); }
262 static String address(Address a) {return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
263 public static String addressList(Object a) {
264 if (a == null) return "NIL";
265 if (a instanceof Address) return "("+address((Address)a)+")";
266 Address[] aa = (Address[])a;
267 StringBuffer ret = new StringBuffer();
269 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
271 return ret.toString();
273 static String flags(Message m) {
275 (m.deleted ? "\\Deleted " : "") +
276 (m.seen ? "\\Seen " : "") +
277 (m.flagged ? "\\Flagged " : "") +
278 (m.draft ? "\\Draft " : "") +
279 (m.answered ? "\\Answered " : "") +
280 (m.recent ? "\\Recent " : "");
282 static String envelope(Message m) {
284 "(" + quotify(m.arrival.toString()) +
285 " " + quotify(m.subject) +
286 " " + addressList(m.from) +
287 " " + addressList(m.headers.get("sender")) +
288 " " + addressList(m.replyto) +
289 " " + addressList(m.to) +
290 " " + addressList(m.cc) +
291 " " + addressList(m.bcc) +
292 " " + quotify((String)m.headers.get("in-reply-to")) +
293 " " + quotify(m.messageid) +
298 Token[] parse(String s) { /* FIXME */ return null; }
305 if (t.type == t.LIST) throw new No("nested queries not yet supported");
306 else if (t.type == t.SET) return Query.set(t.set());
308 if (s.equals("NOT")) { not = true; continue; }
309 if (s.equals("OR")) return Query.or(query(), query());
310 if (s.equals("AND")) return Query.and(query(), query());
313 if (s.startsWith("UN")) { not = true; s = s.substring(2); }
314 if (s.equals("ANSWERED")) q = Query.Flag.ANSWERED;
315 else if (s.equals("DELETED")) q = Query.Flag.DELETED;
316 else if (s.equals("DRAFT")) q = Query.Flag.DRAFT;
317 else if (s.equals("FLAGGED")) q = Query.Flag.FLAGGED;
318 else if (s.equals("RECENT")) q = Query.Flag.RECENT;
319 else if (s.equals("SEEN")) q = Query.Flag.SEEN;
320 else if (s.equals("OLD")) { not = true; q = Query.Flag.RECENT; }
321 else if (s.equals("NEW")) q = Query.and(Query.Flag.RECENT, Query.not(Query.Flag.SEEN));
322 else if (s.equals("KEYWORD")) q = Query.header("keyword", flag());
323 else if (s.equals("HEADER")) q = Query.header(astring(), astring());
324 else if (s.equals("BCC")) q = Query.header("bcc", astring());
325 else if (s.equals("CC")) q = Query.header("cc", astring());
326 else if (s.equals("FROM")) q = Query.header("from", astring());
327 else if (s.equals("TO")) q = Query.header("to", astring());
328 else if (s.equals("SUBJECT")) q = Query.header("subject", astring());
329 else if (s.equals("LARGER")) q = Query.size(n(), true);
330 else if (s.equals("SMALLER")) q = Query.size(n(), false);
331 else if (s.equals("BODY")) q = Query.fullText(astring(), true, false);
332 else if (s.equals("TEXT")) q = Query.fullText(astring(), true, true);
333 else if (s.equals("BEFORE")) q = Query.arrival(date(), true, false);
334 else if (s.equals("SINCE")) q = Query.arrival(date(), false, true);
335 else if (s.equals("ON")) q = Query.arrival(date(), true, true);
336 else if (s.equals("SENTBEFORE")) q = Query.sent(date(), true, false);
337 else if (s.equals("SENTSINCE")) q = Query.sent(date(), false, true);
338 else if (s.equals("SENTON")) q = Query.sent(date(), true, true);
339 else if (s.equals("UID")) q = Query.uid(set());
346 private final String s;
347 private final Token[] l;
349 private static final byte NIL = 0;
350 private static final byte LIST = 1;
351 private static final byte QUOTED = 2;
352 private static final byte NUMBER = 3;
353 private static final byte ATOM = 4;
354 private static final byte BAREWORD = 5;
355 private static final byte SET = 6;
356 public Token() { n = 0; l = null; s = null; type = NIL; }
357 public Token(String quoted) { s = quoted; l = null; type = QUOTED; n = 0; }
358 public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
359 public Token(int number) { n = number; l = null; s = null; type = NUMBER; }
361 // assumes token is a flag list or a fag
362 public void setFlags(Message m) { }
363 public void addFlags(Message m) { }
364 public void deleteFlags(Message m) { }
366 public String mailboxPattern() throws Bad {
367 if (type == ATOM) return s;
368 if (type == QUOTED) return s;
369 throw new Bad("exepected a mailbox pattern");
371 public String flag() throws Bad {
372 if (type != ATOM) throw new Bad("expected a flag");
373 return s; // if first char != backslash, it is a keyword-flag
375 public int n() throws Bad {
376 if (type != NUMBER) throw new Bad("expected number");
379 public int nz() throws Bad {
380 if (type != NUMBER) throw new Bad("expected number");
381 if (n == 0) throw new Bad("expected nonzero number");
384 public String q() throws Bad {
385 if (type == NIL) return null;
386 if (type != QUOTED) throw new Bad("expected qstring");
389 public Token[] l() throws Bad {
390 if (type == NIL) return null;
391 if (type != LIST) throw new Bad("expected parenthesized list");
394 public int[] set() throws Bad {
395 if (type != ATOM) throw new Bad("expected a messageid set");
397 StringTokenizer st = new StringTokenizer(s, ",");
398 while(st.hasMoreTokens()) {
399 String s = st.nextToken();
400 if (s.indexOf(':') != -1) {
401 int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
402 String end_s = s.substring(s.indexOf(':')+1);
403 if (end_s.equals("*")) {
404 ids.addElement(new Integer(start));
405 ids.addElement(new Integer(-1));
407 int end = Integer.parseInt(end_s);
408 for(int j=start; j<=end; j++) ids.addElement(new Integer(j));
411 ids.addElement(new Integer(Integer.parseInt(s)));
414 int[] ret = new int[ids.size()];
415 //ids.copyInto(ret); FIXME
418 public Date date() throws Bad {
419 if (type != QUOTED && type != ATOM) throw new Bad("Expected quoted or unquoted date");
420 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
421 } catch (ParseException p) { throw new Bad("invalid date format; " + p); }
423 public Date datetime() throws Bad {
424 if (type != QUOTED && type != ATOM) throw new Bad("Expected quoted or unquoted datetime");
425 try { return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").parse(s);
426 } catch (ParseException p) { throw new Bad("invalid datetime format; " + p); }
428 public String nstring() throws Bad {
429 if (type == NIL) return null;
430 if (type == QUOTED) return s;
431 throw new Bad("expected NIL or string");
433 public String astring() throws Bad {
434 if (type == ATOM) return s;
435 if (type == QUOTED) return s;
436 throw new Bad("expected atom or string");
438 public String atom() throws Bad {
439 if (type != ATOM) throw new Bad("expected atom");
440 for(int i=0; i<s.length(); i++) {
441 char c = s.charAt(i);
442 if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*')
443 throw new Bad("invalid char in atom: " + c);
447 public Mailbox mailbox() throws Bad, IOException {
448 if (type == BAREWORD && s.toLowerCase().equals("inbox")) return getMailbox("INBOX", false);
449 return getMailbox(astring(), false);
454 public char getc() throws IOException {
456 if (ret == -1) throw new EOFException();
459 public char peekc() throws IOException {
461 if (ret == -1) throw new EOFException();
465 public void fill(byte[] b) throws IOException {
467 while (num < b.length) {
468 int numread = is.read(b, num, b.length - num);
469 if (numread == -1) throw new EOFException();
474 public Token token() {
476 Vec toks = new Vec();
477 StringBuffer sb = new StringBuffer();
478 char c = getc(); while (c == ' ') c = getc();
480 while(peekc() != '}') sb.append(getc());
481 int octets = Integer.parseInt(sb.toString());
482 while(peekc() == ' ') getc(); // whitespace
483 while (getc() != '\n') { }
484 byte[] bytes = new byte[octets];
486 return new Token(new String(bytes));
487 } else if (c == '\"') {
490 if (c == '\\') sb.append(getc());
491 else if (c == '\"') break;
494 } else if (c == ')') {
496 } else if (c == '(') {
498 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
499 Token[] ret = new Token[toks.size()];
501 return null; // FIXME
504 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '{') break;
507 //return toks.toArray();
508 return null; // FIXME
509 } catch (IOException e) {
515 public String mailboxPattern() throws Bad { return token().mailboxPattern(); }
516 public String flag() throws Bad { return token().flag(); }
517 public int n() throws Bad { return token().n(); }
518 public int nz() throws Bad { return token().nz(); }
519 public String q() throws Bad { return token().q(); }
520 public Token[] l() throws Bad { return token().l(); }
521 public int[] set() throws Bad { return token().set(); }
522 public Date date() throws Bad { return token().date(); }
523 public Date datetime() throws Bad { return token().datetime(); }
524 public String nstring() throws Bad { return token().nstring(); }
525 public String astring() throws Bad { return token().astring(); }
526 public String atom() throws Bad { return token().atom(); }
527 public Mailbox mailbox() throws Bad, IOException { return token().mailbox(); }