1 package org.ibex.mail.protocol;
6 // FEATURE: support [charset]
7 public class IMAP extends MessageProtocol {
9 public static void main(String[] args) throws Exception {
10 ServerSocket ss = new ServerSocket(143);
12 System.out.println("listening");
13 final Socket s = ss.accept();
14 System.out.println("connected");
19 } catch (Exception e) {
27 private static class Listener extends Incoming {
30 Mailbox selected = null;
31 public void init() { }
32 public Listener(Socket conn, String vhost) { this.vhost = vhost; this.conn = conn; this.selected = null; }
34 public void login(String user, String password) { if (!auth(user, password)) throw new No("Liar, liar, pants on fire."); }
35 public void capability() { star("CAPABILITY IMAP4rev1"); ok("Completed"); }
36 public void noop() { ok("Completed"); }
37 public void logout() { star("BYE LOGOUT received"); ok("Completed"); }
38 public void delete(Mailbox m) { if (!m.getName().toLowerCase().equals("inbox")) m.delete(); }
39 public void subscribe(String[] args) { ok("SUBSCRIBE ignored"); }
40 public void unsubscribe(String[] args) { ok("UNSUBSCRIBE ignored"); }
41 public void check(String[] args, boolean examineOnly) { ok("check complete"); }
42 public void lsub(String[] args) { list(args); }
43 public void list(String[] args) { star("LIST () \".\" INBOX"); ok("LIST completed"); }
44 public void create(String mailbox) {
45 if (mailbox.charAt(mailbox.length() - 1) != '.' &&
46 !mailbox.toLowerCase.equals("inbox"))
47 if (!storage.create(mailbox))
48 throw No("unable to CREATE mailbox");
49 ok("CREATE completed");
51 public void rename(Mailbox from, String to) {
52 if (from.getName().toLowerCase().equals("inbox")) {
53 int[] messages = from.list();
54 Malbox toBox = getMailbox(to);
55 for(int i=0; i<messages.length; i++) {
56 Message m = from.get(messages[i]);
58 from.delete(messages[i]);
60 } else if (to.toLowerCase().equals("inbox")) {
61 int[] messages = from.list();
62 Mailbox inbox = getMailbox("inbox");
63 for(int i=0; i<messages.length; i++) {
64 Message m = from.get(messages[i]);
66 from.delete(messages[i]);
74 public void status(Mailbox mbox, boolean messages, boolean recent, boolean uidnext, boolean uidvalidity, boolean unseen) {
75 for(int i=0; i<toks.length; i++) {
76 if (toks[i].equals("MESSAGES")) messages = true;
77 else if (toks[i].equals("RECENT")) recent = true;
78 else if (toks[i].equals("UIDNEXT")) uidnext = true;
79 else if (toks[i].equals("UIDVALIDITY")) uidvalidity = true;
80 else if (toks[i].equals("UNSEEN")) unseen = true;
82 int[] messages = mbox.list();
83 int numRecent = 0, numUnseen = 0;
84 for(int i=0; i<messages.length; i++) {
85 Message m = mbox.get(messages[i]);
86 if (!m.seen) numUnseen++;
87 if (m.recent) numRecent++;
89 star("STATUS " + args[0] + " (" +
90 (messages ? ("MESSAGES " + messages.length + " ") : "") +
91 (recent ? ("RECENT " + numRecent + " ") : "") +
92 (unseen ? ("UNSEEN " + numUnseen + " ") : "") +
93 (uidvalidity ? ("UIDVALIDITY " + mbox.uidvalidity + " ") : "") +
94 (uidnext ? ("UIDNEXT " + mbox.uidnext + " ") : "") + ")");
97 public void select(String[] args, boolean examineOnly) {
98 if (args.length < 1) throw new Bad("Not enough arguments");
99 selected = geMailbox(args[0]);
100 if (selected == null) throw new No("No such mailbox");
103 star("OK [UNSEEN 12] Message 12 is first unseen");
104 star("OK [UIDVALIDITY 123123123] UIDs valid");
105 star("FLAGS (\Answered \Flagged \Deleted \Seen \Draft)");
106 ok("[READ-WRITE] " + (examineOnly ? "EXAMINE" : "SELECT") + " completed");
108 public void close(String[] args, boolean examineOnly) {
109 if (selected == null) throw new Bad("no mailbox selected");
110 expunge(new String[] { }, false, true);
112 ok("CLOSE completed");
114 public void expunge(String[] args, boolean examineOnly, boolean silent) {
115 if (selected == null) throw new Bad("no mailbox selected");
116 int[] messages = selected.list();
117 for(int i=0; i<messages.length; i++) {
118 Message m = selected.get(messages[i]);
120 if (!silent) star(m.uid + " EXPUNGE");
121 if (!examineOnly) selected.delete(i);
124 if (!silent) ok("EXPUNGE completed");
127 public void fetch(int[] messageSet, boolean examineOnly, boolean uid) {
128 if (selected == null) throw new Bad("no mailbox selected");
129 Object[] tokens = tokenize(args[0]);
131 boolean negateHeaders;
133 boolean internalDate;
138 for(int i=0; i<tokens.length; i++) {
141 for(int i=0; i<messageSet.length; i++) {
142 Message m = uid ? selected.getUID(messageSet[i]) : selected.get(messageSet[i]);
145 boolean negateHeaders,
147 boolean internalDate,
156 public void append(Mailbox m, Token flags, Date arrived, String literal) {
157 Message m = new Message(null, null, new StringReader(literal));
158 if (flags != null) flags.setFlags(m);
159 if (arrived != null) m.arrival = arrived;
163 public void copy(int[] set, Mailbox target) {
164 for(int i=0; i<set.length; i++) {
165 Message m = selected.get(set[i]);
166 target.add(m); // sharing problem? immutability helps
170 public boolean handleRequest(LineReader r, PrintWriter pw) {
171 pw.println("* OK " + vhost + " " + IMAP.class.getName() + " IMAP4 v0.1 server ready");
174 String s = r.readLine();
175 if (s.indexOf(' ') == -1) { pw.println("* BAD Invalid tag"); continue; }
177 String command = atom();
178 if (command.equals("UID")) { uid = true; command = atom(); }
179 if (command.equals("AUTHENTICATE")) { authenticate(args); }
180 else if (command.equals("LIST")) list(mailbox(), mailboxPattern());
181 else if (command.equals("LSUB")) lsub(mailbox(), mailboxPattern());
182 else if (command.equals("CAPABILITY")) { capability(); }
183 else if (command.equals("LOGIN")) login(astring(), astring());
184 else if (command.equals("LOGOUT")) { logout(); conn.close(); return false; }
185 else if (command.equals("RENAME")) rename(mailbox(), atom());
186 else if (command.equals("APPEND")) {
187 Mailbox m = mailbox();
189 Token[] flags = null;
191 if (t.type == LIST) { flags = t.l(); t = token(); }
192 if (t.type == QUOTED) arrival = datetime();
193 append(m, flags, arrival, literal());
194 } else if (command.equals("EXAMINE")) examine(mailbox());
195 else if (command.equals("COPY")) copy(set(), mailbox());
196 else if (command.equals("DELETE")) delete(mailbox());
197 else if (command.equals("CREATE")) create(mailbox());
198 else if (command.equals("STORE")) {
199 int[] messages = set();
200 String what = atom();
202 for(int i=0; i<messages.length; i++) {
203 Message m = selected.get(messages[i]);
204 if (what.charAt(0) == 'F') m.deleted = m.seen = m.flagged = m.draft = m.answered = m.recent = false;
205 for(int i=0; i<flags.length; i++) {
206 String flag = flags[i].flag();
207 if (flag.equals("Deleted")) m.deleted = what.charAt(0) != '-';
208 if (flag.equals("Seen")) m.seen = what.charAt(0) != '-';
209 if (flag.equals("Flagged")) m.flagged = what.charAt(0) != '-';
210 if (flag.equals("Draft")) m.draft = what.charAt(0) != '-';
211 if (flag.equals("Answered")) m.answered = what.charAt(0) != '-';
212 if (flag.equals("Recent")) m.recent = what.charAt(0) != '-';
214 selected.add(m); // re-add
216 } else if (command.equals("FETCH")) {
220 boolean envelope = false, internaldate = false, size = false, flags = false, uid=false;
221 if (t.type == Token.LIST) tl = t.l();
222 else if (t.atom().equals("FULL")) { flags=true; internaldate=true; size=true; envelope=true; body=true; }
223 else if (t.atom().equals("ALL")) { flags=true; internaldate=true; size=true; envelope=true; }
224 else if (t.atom().equals("FAST")) { flags=true; internaldate=true; size=true; }
225 else tl = new Token[] { t };
226 else throw new Bad("expected atom or list");
227 for (int i=0; i<tl.length; i++) {
228 String s = tl[i].atom();
229 if (s.equals("1")) s = "RFC822";
230 else if (s.startsWith("1.")) s = s.substring(2);
231 if (s.equals("ENVELOPE")) envelope = true;
232 else if (s.equals("FLAGS")) flags = true;
233 else if (s.equals("INTERNALDATE")) internaldate = true;
234 else if (s.equals("RFC822")) body = true; // FIXME: special return syntax?
235 else if (s.equals("RFC822.HEADER")) header = true;
236 else if (s.equals("RFC822.SIZE")) size = true;
237 else if (s.equals("RFC822.TEXT")) body = true;
238 else if (s.equals("BODY")) body = true;
239 else if (s.equals("BODYSTRUCTURE")) throw new No("FETCH BODYSTRUCTURE not supported");
240 else if (s.equals("UID")) uid = true;
241 else if (s.startsWith("BODY")) throw new No("FETCH BODY[*] not supported");
242 else throw new Bad("unrecognized FETCH argument \"" + s + "\"");
244 fetch(selected, null, false, flags, internaldate, size, uid, start, end, setseen, envelope);
245 } else if (command.equals("STATUS")) {
246 Mailbox m = mailbox();
248 boolean messages = false;
249 boolean recent = false;
250 boolean uidnext = false;
251 boolean uidvalidity = false;
252 boolean unseen = false;
253 for(int i=0; i<attrs.length; i++) {
254 String s = attrs[i].atom();
255 if (s.equals("MESSAGES")) messages = true;
256 if (s.equals("RECENT")) recent = true;
257 if (s.equals("UIDNEXT")) uidnext = true;
258 if (s.equals("UIDVALIDITY")) uidvalidity = true;
259 if (s.equals("UNSEEN")) unseen = true;
261 status(mbox, messages, recent, uidnext, uidvalidity, unseen);
263 throw new Bad("unrecognized command \"" + command + "\"");
269 public static String quotify(String s){return s==null?"NIL":"\""+s.replaceAll("\\\\", "\\\\").replaceAll("\"", "\\\\\"")+"\"";}
270 public static String address(Address a) { return "("+quotify(a.desciption)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
271 public static String addressList(Object a) {
272 if (a == null) return "NIL";
273 if (a instanceof Address) return "("+address((Address)a)+")";
274 Address[] aa = (Address[])a;
275 StringBuffer ret = new StringBuffer();
277 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
279 return ret.toString();
282 public static String envelope(Message m) {
284 "(" + quotify(m.arrival.toString()) +
285 " " + quotify(m.subject) +
286 " " + addressList(m.from) +
287 " " + addressList(m.sender) +
288 " " + addressList(m.replyTo) +
289 " " + addressList(m.to) +
290 " " + addressList(m.cc) +
291 " " + addressList(m.bcc) +
292 " " + quotify(m.headers.get("in-reply-to")) +
293 " " + quotify(m.messageId) +
297 public static void fetch(Message m, String[] headers, boolean negateHeaders, boolean flags, boolean internalDate,
298 boolean size, boolean uid, int start, int end, boolean setSeen, boolean envelope) {
303 + m.deleted ? "\Deleted " : ""
304 + m.seen ? "\Seen " : ""
305 + m.flagged ? "\Flagged " : ""
306 + m.draft ? "\Draft " : ""
307 + m.answered ? "\Answered " : ""
308 + m.recent ? "\Recent " : ""
310 if (size) reply += "RFC822.SIZE " m.rfc822size() + " ";;
311 if (bodyStructure) // FIXME
312 reply += "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"US-ASCII\") NIL NIL \"7BIT\" " + m.rfc822size() +" "+ m.numLines() +")";
315 "(" + quotify(m.date) +
316 " " + quotify(m.subject) +
317 " " + quotify(new Address[] { m.from }) + " " +
318 " " + quotify(new Address[] { m.sender }) + " " +
319 " " + quotify(new Address[] { m.replyTo }) + " " +
320 " " + quotify(new Address[] { m.to }) + " " +
321 " " + quotify(cc) + " " +
322 " " + quotify(bcc) + " " +
323 " " + quotify(m.headers.get("in-reply-to")) + " " +
324 " " + quotify(m.messageId) +
326 if (internaldate) reply += quotify(m.arrival) + " ";
330 public static Query parseQuery() {
335 if (t.type == t.LIST) { }
336 else if (t.type == t.SET) { }
338 if (tok.equals("NOT")) { not = true; continue; }
339 if (tok.equals("OR")) { /* FIXME */ }
340 if (tok.equals("AND")) { /* FIXME */ }
343 if (tok.startsWith("UN")) { not = true; tok = tok.substring(2); }
344 if (tok.equals("ANSWERED")) q = new Query.Flag(Query.Flag.ANSWERED);
345 else if (tok.equals("DELETED")) q = new Query.Flag(Query.Flag.ANSWERED);
346 else if (tok.equals("DRAFT")) q = new Query.Flag(Query.Flag.ANSWERED);
347 else if (tok.equals("FLAGGED")) q = new Query.Flag(Query.Flag.ANSWERED);
348 else if (tok.equals("RECENT")) q = new Query.Flag(Query.Flag.ANSWERED);
349 else if (tok.equals("SEEN")) q = new Query.Flag(Query.Flag.ANSWERED);
350 else if (tok.equals("OLD")) { not = true; q = new Query.Flag(Query.Flag.RECENT); }
351 else if (tok.equals("NEW")) q = new Query.And(new Query.Flag(Query.Flag.RECENT),
352 new Query.Not(new Query.Flag(Query.Flag.SEEN)));
353 else if (tok.equals("KEYWORD")) q = new Query.Header("keyword", flag());
354 else if (tok.equals("HEADER")) q = new Query.Header(astring(), astring());
355 else if (tok.equals("BCC")) q = new Query.Header("bcc", astring());
356 else if (tok.equals("CC")) q = new Query.Header("cc", astring());
357 else if (tok.equals("FROM")) q = new Query.Header("from", astring());
358 else if (tok.equals("TO")) q = new Query.Header("to", astring());
359 else if (tok.equals("SUBJECT")) q = new Query.Header("subject", astring());
360 else if (tok.equals("BEFORE")) q = new Query.Arrival(date(), true, false);
361 else if (tok.equals("SINCE")) q = new Query.Arrival(date(), false, true);
362 else if (tok.equals("ON")) q = new Query.Arrival(date(), true, true);
363 else if (tok.equals("LARGER")) q = new Query.Size(n(), true);
364 else if (tok.equals("SMALLER")) q = new Query.Size(n(), false);
365 else if (tok.equals("BODY")) q = new Query.FullText(astring(), true, false);
366 else if (tok.equals("TEXT")) q = new Query.FullText(astring(), true, true);
367 else if (tok.equals("SENTBEFORE")) { /* FIXME date() */ }
368 else if (tok.equals("SENTSINCE")) { /* FIXME date() */ }
369 else if (tok.equals("SENTON")) { /* FIXME date() */ }
370 else if (tok.equals("UID")) { /* FIXME set() */ }
373 private static class Token {
375 private final String s;
376 private final Token[] l;
378 private static final byte NIL = 0;
379 private static final byte LIST = 1;
380 private static final byte QUOTED = 2;
381 private static final byte NUMBER = 3;
382 public Token() { n = 0; list = null; s = null; type = NIL; }
383 public Token(String quoted) { s = quoted; l = null; type = QUOTED; n = 0; }
384 public Token(Token[] list) { l = list; s = null; type = LIST; n = 0; }
385 public Token(int number) { n = number; list = null; s = null; type = NUMBER; }
387 // assumes token is a flag list or a fag
388 public void setFlags(Message m) { }
389 public void addFlags(Message m) { }
390 public void deleteFlags(Message m) { }
392 public String mailboxPattern() {
393 /* 1*(ATOM_CHAR / "%" / "*") / string */
395 public String flag() throws Bad {
396 if (type != ATOM) throw new Bad("expected a flag");
397 return s; // if first char != backslash, it is a keyword-flag
399 public int n() throws Bad {
400 if (type != NUMBER) throw new Bad("expected number");
403 public int nz() throws Bad {
404 if (type != NUMBER) throw new Bad("expected number");
405 if (n == 0) throw new Bad("expected nonzero number");
408 public String q() throws Bad {
409 if (type == NIL) return null;
410 if (type != QUOTED) throw new Bad("expected qstring");
413 public String nstring() throws Bad {
415 public Token[] l() throws Bad {
416 if (type == NIL) return null;
417 if (type != LIST) throw new Bad("expected parenthesized list");
420 public int[] set() throws Bad {
421 // FIXME <set>,<set> <n> <n>:<n> * (* = largest)
423 public Date date() throws Bad {
424 // may be quoted or unquoted
426 new SimpleDateFormat("dd-MMM-yyyy").parse(s);
427 } catch (DateParsingException) {
430 public String nstring() throws Bad {
431 if (type == NIL) return null;
432 if (type == QUOTED) return s;
433 throw new Bad("expected NIL or string");
435 public String astring() throws Bad {
436 if (type == ATOM) return s;
437 if (type == QUOTED) return s;
438 throw new Bad("expected atom or string");
440 public String atom() throws Bad {
441 // ATOM_CHAR ::= <any CHAR except atom_specials>
442 // atom_specials ::= "(" / ")" / "{" / SPACE / CTL / list_wildcards / quoted_specials
443 if (type != ATOM) throw new Bad("expected atom");
445 public Mailbox mailbox() throws Bad {
446 if (type == BAREWORD && s.toLowerCase().equals("inbox")) return Mailbox.INBOX;
447 return Mailbox.getMailbox(astring());
449 public Date datetime() throws Bad {
450 // expected to be a quoted string
452 new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").parse(s);
459 // literal ::= "{" number "}" CRLF *CHAR8 ;; Number represents the number of CHAR8 octets
461 public static Token[] tokenize(String s) {
462 Vec toks = new Vec();
463 StringBuffer sb = new StringBuffer();
464 for(int i=0; i<s.length();) {
466 if (s.charAt(i) == '\"') {
467 for(i++; i < s.length(); i++) {
468 if (s.charAt(i) == '\\') sb.append(s.charAt(++i));
469 else if (s.charAt(i) == '\"') { i++; break; }
470 else sb.append(s.charAt(i));
472 } else if (s.charAt(i) == '(') {
473 // FIXME, deal with strings within parens
475 for(; i < s.length(); i++)
476 if (s.charAt(i) == ' ' || s.charAt(i) == '\"') break;
477 else sb.append(s.charAt(i));
479 toks.addElement(sb.toString());
480 while (i < s.length() && s.charAt(i) == ' ') i++;
482 return toks.toArray();