1 package org.ibex.mail.protocol;
2 import org.ibex.mail.*;
3 import org.ibex.util.*;
4 import org.ibex.mail.target.*;
10 // FIXME: this is valid LSUB "" asdfdas%*%*%*%*SFEFGWEF
11 // FIXME: be very careful about where/when we quotify stuff
12 // FIXME: 'UID FOO 100:*' must match at least one message even if all UIDs less than 100
13 // FIXME: LIST should return INBOX if applicable
17 // RFC 3501: IMAPv4 with clarifications
21 // FEATURE: make sure we're being case-insensitive enough; probably want to upcase atom()
22 // FEATURE: MIME-queries and BODYSTRUCTURE
23 // FEATURE: READ-WRITE / READ-ONLY status on SELECT
24 // FEATURE: pipelining
25 // FEATURE: support [charset]
27 // FEATURE: subscriptions
28 // FEATURE: tune for efficiency
30 // FEATURE: asynchronous client notifications (need to re-read RFC)
34 public static final float version = (float)0.1;
36 // API Class //////////////////////////////////////////////////////////////////////////////
38 public static final int
39 PEEK=0x1, BODYSTRUCTURE=0x2, ENVELOPE=0x4, FLAGS=0x8, INTERNALDATE=0x10, FIELDS=0x800, FIELDSNOT=0x1000,
40 RFC822=0x20, RFC822TEXT=0x40, RFC822SIZE=0x80, HEADERNOT=0x100, UID=0x200, HEADER=0x400;
42 public static interface Client {
43 public void expunge(int uid);
44 public void list(char separator, String mailbox, boolean lsub, boolean phantom);
45 public void fetch(int num, int flags, int size, Message m, int muid); // m may be null or incomplete
48 public static interface Server {
49 public String[] capability();
50 public Hashtable id(Hashtable clientId);
51 public void copy(Query q, String to);
52 public void login(String u, String p);
54 public void unselect();
55 public void delete(String m);
56 public void create(String m);
57 public void append(String m, int flags, Date arrival, String body);
61 public void subscribe(String mailbox);
62 public void unsubscribe(String mailbox);
63 public int seen(String mailbox);
64 public int recent(String mailbox);
65 public int count(String mailbox);
66 public int uidNext(String mailbox);
67 public int uidValidity(String mailbox);
68 public int[] search(Query q, boolean uid);
69 public void rename(String from, String to);
70 public void select(String mailbox, boolean examineOnly);
71 public void setFlags(Query q, int flags, boolean uid, boolean silent);
72 public void removeFlags(Query q, int flags, boolean uid, boolean silent);
73 public void addFlags(Query q, int flags, boolean uid, boolean silent);
74 public void expunge();
75 public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid);
76 public void lsub(String start, String ref);
77 public void list(String start, String ref);
78 public static interface Authenticator { public abstract Mailbox authenticate(String user, String pass); }
79 public static class Exn extends MailException { public Exn(String s) { super(s); } }
80 public static class Bad extends Exn { public Bad(String s) { super(s); } }
81 public static class No extends Exn { public No(String s) { super(s); } }
85 // MailboxWrapper //////////////////////////////////////////////////////////////////////////////
87 /** wraps an IMAP.Server interface around a Mailbox */
88 public static class MailboxWrapper implements Server {
90 public static final char sep = '.';
93 Mailbox selected = null;
95 Mailbox selected() { if (selected == null) throw new Bad("no mailbox selected"); return selected; }
96 final Server.Authenticator auth;
99 public MailboxWrapper(Server.Authenticator auth, Client c) { this.auth=auth; this.client=c;}
101 private Mailbox mailbox(String name, boolean create) {
102 if (name.equalsIgnoreCase("inbox")) return inbox;
104 for(StringTokenizer st = new StringTokenizer(name, sep + ""); st.hasMoreTokens();)
105 if ((m = m.slash(st.nextToken(), create)) == null) throw new Server.No("no such mailbox " + name);
109 // FEATURE: not accurate when a wildcard and subsequent non-wildcards both match a single component
110 public void lsub(String start, String ref) { list(start, ref, true); }
111 public void list(String start, String ref) { list(start, ref, false); }
112 public void list(String start, String ref, boolean lsub) {
113 if (ref.length() == 0) { client.list(sep, start, lsub, false); return; }
114 while (start.endsWith(""+sep)) start = start.substring(0, start.length() - 1);
115 if (ref.endsWith("%")) ref = ref + sep;
116 String[] children = (start.length() == 0 ? root : mailbox(start, false)).children();
117 for(int i=0; i<children.length; i++) {
118 String s = children[i], pre = ref, kid = start + (start.length() > 0 ? sep+"" : "") + s;
119 boolean phantom = mailbox(kid, false).phantom();
121 if (pre.length() == 0) {
122 if (s.length() == 0) client.list(sep, kid, lsub, phantom);
123 } else switch(pre.charAt(0)) {
124 case sep: if (s.length() == 0) list(kid, pre.substring(1), lsub); break;
125 case '%': client.list(sep,kid,lsub,phantom);pre=pre.substring(1); s = ""; continue;
126 case '*': client.list(sep,kid,lsub,phantom);list(kid,pre,lsub);pre=pre.substring(1); break;
127 default: if (s.length()==0) break;
128 if (s.charAt(0) != pre.charAt(0)) break;
129 s = s.substring(1); pre = pre.substring(1); continue;
136 public String[] capability() { return new String[] { "IMAP4rev1" , "UNSELECT", "ID" }; }
137 public Hashtable id(Hashtable clientId) {
138 Hashtable response = new Hashtable();
139 response.put("name", IMAP.class.getName());
140 response.put("version", version + "");
141 response.put("os", System.getProperty("os.name", null));
142 response.put("os-version", System.getProperty("os.version", null));
143 response.put("vendor", "none");
144 response.put("support-url", "http://mail.ibex.org/");
148 public void copy(Query q, String to) { copy(q, mailbox(to, false)); }
149 /* */ void copy(Query q, Mailbox to) {
150 for(Mailbox.Iterator it=selected().iterator(q);it.next();) to.add(it.cur(), it.flags() | Mailbox.Flag.RECENT); }
152 public void login(String u, String p) {
153 if ((root = auth.authenticate(u,p)) == null) throw new No("Login failed.");
154 inbox = mailbox("INBOX", false); // FEATURE: ??
156 public void unselect() { selected = null; }
157 public void delete(String m0) { delete(mailbox(m0,false)); }
158 public void delete(Mailbox m) { if (!m.equals(inbox)) m.destroy(false); else throw new Bad("can't delete inbox"); }
159 public void create(String m) { mailbox(m, true); }
160 public void append(String m,int f,Date a,String b){mailbox(m,false).add(new Message(null,null,b,a),f|Mailbox.Flag.RECENT);}
161 public void check() { }
162 public void noop() { }
163 public void logout() { }
164 public void close() { for(Mailbox.Iterator it=selected().iterator(Query.deleted()); it.next();) it.delete(); unselect(); }
165 public void expunge() { for(Mailbox.Iterator it = selected().iterator(Query.deleted());it.next();) expunge(it); }
166 public void expunge(Mailbox.Iterator it) { client.expunge(it.uid()); it.delete(); }
167 public void subscribe(String mailbox) { }
168 public void unsubscribe(String mailbox) { }
169 public int seen(String mailbox) { return mailbox(mailbox, false).count(Query.seen()); }
170 public int recent(String mailbox) { return mailbox(mailbox, false).count(Query.recent()); }
171 public int count(String mailbox) { return mailbox(mailbox, false).count(Query.all()); }
172 public int uidNext(String mailbox) { return mailbox(mailbox, false).uidNext(); }
173 public int uidValidity(String mailbox) { return mailbox(mailbox, false).uidValidity(); }
174 public void select(String mailbox, boolean examineOnly) { selected = mailbox(mailbox, false); }
176 public int[] search(Query q, boolean uid) {
177 Vec.Int vec = new Vec.Int();
178 for(Mailbox.Iterator it = selected().iterator(q); it.next();) {
179 vec.addElement(uid ? it.uid() : it.num());
185 public void setFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, 0, silent); }
186 public void addFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, 1, silent); }
187 public void removeFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, -1, silent); }
189 private void doFlags(Query q, int flags, boolean uid, int style, boolean silent) {
190 for(Mailbox.Iterator it = selected().iterator(q);it.next();) {
191 boolean recent = it.recent();
192 if (style == -1) it.removeFlags(flags);
193 else if (style == 0) it.setFlags(flags);
194 else if (style == 1) it.addFlags(flags);
196 if (!silent) client.fetch(it.num(), it.flags(), -1, null, it.uid());
199 public void rename(String from0, String to) {
200 Mailbox from = mailbox(from0, false);
201 if (from.equals(inbox)) { from.copy(Query.all(), mailbox(to, true)); }
202 else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), mailbox(to, true)); from.destroy(false); }
203 else from.rename(to);
205 public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid) {
206 for(Mailbox.Iterator it = selected().iterator(q); it.next(); ) {
207 client.fetch(it.num(), it.flags(), it.cur().rfc822size(), it.cur(), it.uid());
214 // Single Session Handler //////////////////////////////////////////////////////////////////////////////
216 /** takes an IMAP.Server and exposes it to the world as an IMAP server on a TCP socket */
217 public static class Listener extends Parser implements Client {
218 String selectedName = null;
219 Mailbox inbox = null, root = null;
221 public Listener(Socket conn, Server.Authenticator auth) throws IOException {
222 this(conn, java.net.InetAddress.getLocalHost().getHostName(), auth); }
223 public Listener(Socket conn, String vhost, Server.Authenticator auth) throws IOException {
225 this.api = new IMAP.MailboxWrapper(auth, this);
228 private Token[] lastfetch = null; // hack
229 private boolean lastuid = false; // hack
231 private boolean selected = false;
232 private void selected() { if (!selected) throw new Server.Bad("no mailbox selected"); }
233 private void star(String s) { try { println("* " + s); } catch (IOException e) { throw new MailException.IOException(e); } }
234 private String qq(String s) { return Printer.qq(s); }
236 // Callbacks //////////////////////////////////////////////////////////////////////////////
238 public void expunge(int uid) { star(uid + " EXPUNGE"); }
239 public void list(char sep, String box, boolean lsub, boolean phantom)
240 {star((lsub?"LSUB":"LIST")+" ("+(phantom?"\\Noselect":"")+") \""+sep+"\" \""+box+"\"");}
241 public void fetch(int num, int flags, int size, Message m, int muid) {
242 fetch(m, lastfetch, num, flags, size, lastuid, muid); }
245 * Parse a fetch request <i>or</i> emit a fetch reply.
247 * To avoid duplicating tedious parsing logic, this function
248 * performs both of the following tasks:
249 * - parse the fetch request in Token[] t and return a fetch spec
250 * - emit a fetch reply for the parsed spec with respect to message m
252 private void fetch(Object o, Token[] t, int num, int flags, int size, boolean uid, int muid) {
253 Query q = o instanceof Query ? (Query)o : null;
254 Message m = o instanceof Message ? (Message)o : null;
255 boolean e = m != null;
258 int spec = 0; // spec; see constants for flags
259 String[] headers = null;
260 int start = -1, end = -1;
261 StringBuffer r = new StringBuffer();
262 if (e) { r.append(num); r.append(" FETCH ("); }
263 int initlen = r.length();
265 boolean good = false;
266 for(int i=0; i<t.length; i++)
267 if ((t[i].type == Token.QUOTED || t[i].type == Token.ATOM) &&
268 t[i].astring().equalsIgnoreCase("UID")) good = true;
270 Token[] t2 = new Token[t.length + 1];
271 System.arraycopy(t, 0, t2, 0, t.length);
272 t2[t2.length - 1] = new Token("UID");
276 if (t.length == 0 && (t[0].type == Token.QUOTED || t[0].type == Token.ATOM)) {
277 if (t[0].astring().equalsIgnoreCase("ALL"))
278 t = new Token[] { new Token("FLAGS"), new Token("INTERNALDATE"),
279 new Token("ENVELOPE"), new Token("RFC822.SIZE") };
280 else if (t[0].astring().equalsIgnoreCase("FULL"))
281 t = new Token[] { new Token("FLAGS"), new Token("INTERNALDATE"), new Token("BODY"),
282 new Token("ENVELOPE"), new Token("RFC822.SIZE") };
283 else if (t[0].astring().equalsIgnoreCase("FAST"))
284 t = new Token[] { new Token("FLAGS"), new Token("INTERNALDATE"),
285 new Token("RFC822.SIZE") };
287 for(int i=0; i<t.length; i++) {
288 if (r.length() > initlen) r.append(" ");
289 if (t[i] == null || t[i].s == null) continue;
290 String s = t[i].s.toUpperCase();
291 r.append(s.equalsIgnoreCase("BODY.PEEK")?"BODY":s);
292 if (s.equals("BODYSTRUCTURE")) { spec|=BODYSTRUCTURE;if(e){r.append(" ");r.append(Printer.bodystructure(m));}
293 } else if (s.equals("ENVELOPE")) { spec|=ENVELOPE; if(e){r.append(" ");r.append(Printer.envelope(m));}
294 } else if (s.equals("FLAGS")) { spec|=FLAGS; if(e){r.append(" ");r.append(Printer.flags(flags));}
295 } else if (s.equals("INTERNALDATE")) { spec|=INTERNALDATE; if(e){r.append(" ");r.append(Printer.date(m.arrival));}
296 } else if (s.equals("RFC822")) { spec|=RFC822; if(e){r.append(" ");r.append(Printer.message(m));}
297 } else if (s.equals("RFC822.TEXT")) { spec|=RFC822TEXT; if(e){r.append(" ");r.append(qq(m.body));}
298 } else if (s.equals("RFC822.HEADER")){ spec|=HEADER; if(e){r.append(" ");r.append(qq(m.allHeaders+"\r\n"));}
299 } else if (s.equals("RFC822.SIZE")) { spec|=RFC822SIZE; if(e){r.append(" ");r.append(m.rfc822size());}
300 } else if (s.equals("UID")) { spec|=UID; if(e){r.append(" ");r.append(muid); }
301 } else if (!(s.equals("BODY.PEEK") || s.equals("BODY"))) { throw new Server.No("unknown fetch argument: " + s);
303 if (s.equalsIgnoreCase("BODY.PEEK")) spec |= PEEK;
304 else if (e) api.addFlags(Query.num(new int[] { num, num }), Mailbox.Flag.SEEN, false, false);
305 if (i<t.length - 1 && (t[i+1].type == Token.LIST)) {if (e){r.append(" ");r.append(qq(m.body));} continue; }
308 Token[] list = t[++i].l();
309 s = list.length == 0 ? "" : list[0].s.toUpperCase();
311 if (list.length == 0) { spec |= RFC822TEXT; if(e) payload = m.body; }
312 else if (s.equals("")) { spec |= RFC822TEXT; if(e) payload = m.body; }
313 else if (s.equals("TEXT")) { spec |= RFC822TEXT; if(e) payload = m.body; }
314 else if (s.equals("HEADER")) { spec |= HEADER; if(e) payload = m.allHeaders+"\r\n"; }
315 else if (s.equals("HEADER.FIELDS")) { spec |= FIELDS; payload=headers(r,t[i].l()[1].sl(),false,m,e); }
316 else if (s.equals("HEADER.FIELDS.NOT")) { spec |= FIELDSNOT; payload=headers(r,t[i].l()[1].sl(),true,m,e); }
317 else if (s.equals("MIME")) { throw new Server.Bad("MIME not supported"); }
318 else throw new Server.Bad("unknown section type " + s);
319 if (i<t.length - 1 && (t[i+1].s != null && t[i+1].s.startsWith("<"))) {
321 s = t[i].s.substring(1, t[i].s.indexOf('>'));
322 int dot = s.indexOf('.');
323 start = dot == -1 ? Integer.parseInt(s) : Integer.parseInt(s.substring(0, s.indexOf('.')));
324 end = dot == -1 ? -1 : Integer.parseInt(s.substring(s.indexOf('.') + 1));
325 if (e) { payload = payload.substring(start, Math.min(end+1,payload.length())); r.append("<"+start+">"); }
327 if (e) { r.append(" "); r.append(qq(payload)); }
330 if (e) { r.append(")"); star(r.toString()); } else api.fetch(q, spec, headers, start, end, uid);
333 private String headers(StringBuffer r, String[] headers, boolean negate, Message m, boolean e) {
335 if (e) r.append(" (");
337 if(e) for(int j=0; j<headers.length; j++) {
338 r.append(headers[j] + (j<headers.length-1?" ":""));
339 if (m.headers.get(headers[j]) != null) payload += headers[j]+": "+m.headers.get(headers[j])+"\r\n";
342 if (e) for(int j=0; j<headers.length; j++) r.append(headers[j] + (j<headers.length-1?" ":""));
343 if(e) { OUTER: for(Enumeration x=m.headers.keys(); x.hasMoreElements();) {
344 String key = (String)x.nextElement();
345 for(int j=0; j<headers.length; j++) if (key.equalsIgnoreCase(headers[j])) continue OUTER;
346 payload += key + ": " + m.headers.get(key)+"\r\n";
349 if (e) r.append(")]");
350 return payload + "\r\n";
353 public boolean handleRequest() throws IOException {
354 star("OK " + vhost + " " + IMAP.class.getName() + " IMAP4rev1 [RFC3501] v" + version + " server ready");
355 for(String tag = null;; newline()) try {
358 tag = null; tag = token().astring();
359 String command = token().atom();
360 if (command.equalsIgnoreCase("UID")) { uid = true; command = token().atom(); }
361 int commandKey = ((Integer)commands.get(command.toUpperCase())).intValue();
363 case LOGIN: api.login(token().astring(), token().astring()); break;
364 case CAPABILITY: star("CAPABILITY " + Printer.join(" ", api.capability())); break;
365 case AUTHENTICATE: throw new Server.No("AUTHENTICATE not supported");
366 case LOGOUT: api.logout(); star("BYE"); conn.close(); return false;
367 case LIST: api.list(token().q(), token().q()); break;
368 case LSUB: api.lsub(token().q(), token().q()); break;
369 case SUBSCRIBE: api.subscribe(token().astring()); break;
370 case UNSUBSCRIBE: api.unsubscribe(token().astring()); break;
371 case RENAME: api.rename(token().astring(), token().astring()); break;
372 case EXAMINE: api.select(token().astring(), true); break;
373 case COPY: selected(); api.copy(Query.set(uid, token().set()), token().astring()); break;
374 case DELETE: api.delete(token().atom()); break;
375 case CHECK: selected(); api.check(); break;
376 case NOOP: api.noop(); break;
377 case CLOSE: selected(); api.close(); break;
378 case EXPUNGE: selected(); api.expunge(); break;
379 case UNSELECT: selected(); api.unselect(); selected = false; break;
380 case CREATE: api.create(token().astring()); break;
381 case FETCH: selected(); lastuid=uid; fetch(Query.set(uid, token().set()), lastfetch = token().l(), 0, 0, 0, uid, 0); break;
382 case SEARCH: selected(); star("SEARCH " + Printer.join(api.search(query(), uid))); break;
384 String mailbox = token().astring();
385 api.select(mailbox, false);
386 star("FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
387 star(api.count(mailbox) + " EXISTS");
388 star(api.recent(mailbox) + " RECENT");
389 star("OK [UIDVALIDITY " + api.uidValidity(mailbox) + "] UIDs valid");
390 star("OK [UIDNEXT " + api.uidNext(mailbox) + "]");
391 star("OK [PERMANENTFLAGS (\\Seen \\Draft \\Answered \\Deleted)]");
395 String mailbox = token().atom();
396 Token[] list = token().l();
397 String response = "";
398 for(int i=0; i<list.length; i++) {
399 String s = list[i].atom().toUpperCase();
400 if (s.equals("MESSAGES")) response += "MESSAGES " + api.count(mailbox);
401 if (s.equals("RECENT")) response += "RECENT " + api.seen(mailbox);
402 if (s.equals("UIDNEXT")) response += "UNSEEN " + api.recent(mailbox);
403 if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + api.uidValidity(mailbox);
404 if (s.equals("UNSEEN")) response += "UIDNEXT " + api.uidNext(mailbox);
406 star("STATUS " + selectedName + " (" + response + ")");
410 String m = token().atom();
414 if (t.type == t.LIST) { flags = t.flags(); t = token(); }
415 if (t.type == t.QUOTED) { arrival = t.datetime(); t = token(); }
416 api.append(m, flags, arrival, token().q());
420 Query q = uid ? Query.uid(token().set()) : Query.num(token().set());
421 String s = token().atom().toUpperCase();
422 int flags = token().flags();
423 if (s.equals("FLAGS")) api.setFlags(q, flags, uid, false);
424 else if (s.equals("+FLAGS")) api.addFlags(q, flags, uid, false);
425 else if (s.equals("-FLAGS")) api.removeFlags(q, flags, uid, false);
426 else if (s.equals("FLAGS.SILENT")) api.setFlags(q, flags, uid, true);
427 else if (s.equals("+FLAGS.SILENT")) api.addFlags(q, flags, uid, true);
428 else if (s.equals("-FLAGS.SILENT")) api.removeFlags(q, flags, uid, true);
429 else throw new Server.Bad("unknown STORE specifier " + s);
431 default: throw new Server.Bad("unrecognized command \"" + command + "\"");
433 println(tag+" OK "+command+" Completed. " +
434 (commandKey == LOGIN ? ("[CAPABILITY "+Printer.join(" ", api.capability())+"]") : ""));
435 } catch (Server.Bad b) { println(tag==null ? "* BAD Invalid tag":(tag + " Bad " + b.toString())); b.printStackTrace();
436 } catch (Server.No n) { println(tag==null?"* BAD Invalid tag":(tag+" No " + n.toString())); n.printStackTrace(); }
439 private static final Hashtable commands = new Hashtable();
440 private static final int UID = 0; static { commands.put("UID", new Integer(UID)); }
441 private static final int AUTHENTICATE = 1; static { commands.put("AUTHENTICATE", new Integer(AUTHENTICATE)); }
442 private static final int LIST = 2; static { commands.put("LIST", new Integer(LIST)); }
443 private static final int LSUB = 3; static { commands.put("LSUB", new Integer(LSUB)); }
444 private static final int SUBSCRIBE = 4; static { commands.put("SUBSCRIBE", new Integer(SUBSCRIBE)); }
445 private static final int UNSUBSCRIBE = 5; static { commands.put("UNSUBSCRIBE", new Integer(UNSUBSCRIBE)); }
446 private static final int CAPABILITY = 6; static { commands.put("CAPABILITY", new Integer(CAPABILITY)); }
447 private static final int ID = 7; static { commands.put("ID", new Integer(ID)); }
448 private static final int LOGIN = 8; static { commands.put("LOGIN", new Integer(LOGIN)); }
449 private static final int LOGOUT = 9; static { commands.put("LOGOUT", new Integer(LOGOUT)); }
450 private static final int RENAME = 10; static { commands.put("RENAME", new Integer(RENAME)); }
451 private static final int EXAMINE = 11; static { commands.put("EXAMINE", new Integer(EXAMINE)); }
452 private static final int SELECT = 12; static { commands.put("SELECT", new Integer(SELECT)); }
453 private static final int COPY = 13; static { commands.put("COPY", new Integer(COPY)); }
454 private static final int DELETE = 14; static { commands.put("DELETE", new Integer(DELETE)); }
455 private static final int CHECK = 15; static { commands.put("CHECK", new Integer(CHECK)); }
456 private static final int NOOP = 16; static { commands.put("NOOP", new Integer(NOOP)); }
457 private static final int CLOSE = 17; static { commands.put("CLOSE", new Integer(CLOSE)); }
458 private static final int EXPUNGE = 18; static { commands.put("EXPUNGE", new Integer(EXPUNGE)); }
459 private static final int UNSELECT = 19; static { commands.put("UNSELECT", new Integer(UNSELECT)); }
460 private static final int CREATE = 20; static { commands.put("CREATE", new Integer(CREATE)); }
461 private static final int STATUS = 21; static { commands.put("STATUS", new Integer(STATUS)); }
462 private static final int FETCH = 22; static { commands.put("FETCH", new Integer(FETCH)); }
463 private static final int APPEND = 23; static { commands.put("APPEND", new Integer(APPEND)); }
464 private static final int STORE = 24; static { commands.put("STORE", new Integer(STORE)); }
465 private static final int SEARCH = 25; static { commands.put("SEARCH", new Integer(SEARCH)); }
468 public abstract static class Parser extends Connection {
469 public Parser(Socket conn, String vhost) throws IOException { super(conn, vhost); }
470 protected Query query() {
476 if (t.type == t.LIST) throw new Server.No("nested queries not yet supported FIXME");
477 else if (t.type == t.SET) return Query.num(t.set());
478 s = t.atom().toUpperCase();
479 if (s.equals("NOT")) { not = true; continue; }
480 if (s.equals("OR")) return Query.or(query(), query()); // FIXME parse rest of list
481 if (s.equals("AND")) return Query.and(query(), query());
484 if (s.startsWith("UN")) { not = true; s = s.substring(2); }
485 if (s.equals("ANSWERED")) q = Query.answered();
486 else if (s.equals("DELETED")) q = Query.deleted();
487 else if (s.equals("ALL")) q = Query.all();
488 else if (s.equals("DRAFT")) q = Query.draft();
489 else if (s.equals("FLAGGED")) q = Query.flagged();
490 else if (s.equals("RECENT")) q = Query.recent();
491 else if (s.equals("SEEN")) q = Query.seen();
492 else if (s.equals("OLD")) { not = true; q = Query.recent(); }
493 else if (s.equals("NEW")) q = Query.and(Query.recent(), Query.not(Query.seen()));
494 else if (s.equals("KEYWORD")) q = Query.header("keyword", token().flag());
495 else if (s.equals("HEADER")) q = Query.header(token().astring(), token().astring());
496 else if (s.equals("BCC")) q = Query.header("bcc", token().astring());
497 else if (s.equals("CC")) q = Query.header("cc", token().astring());
498 else if (s.equals("FROM")) q = Query.header("from", token().astring());
499 else if (s.equals("TO")) q = Query.header("to", token().astring());
500 else if (s.equals("SUBJECT")) q = Query.header("subject", token().astring());
501 else if (s.equals("LARGER")) q = Query.size(token().n(), Integer.MAX_VALUE);
502 else if (s.equals("SMALLER")) q = Query.size(Integer.MIN_VALUE, token().n());
503 else if (s.equals("BODY")) q = Query.body(token().astring());
504 else if (s.equals("TEXT")) q = Query.full(token().astring());
505 else if (s.equals("BEFORE")) q = Query.arrival(new Date(0), token().date());
506 else if (s.equals("SINCE")) q = Query.arrival(token().date(), new Date(Long.MAX_VALUE));
507 else if (s.equals("ON")) { Date d = token().date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
508 else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), token().date());
509 else if (s.equals("SENTSINCE")) q = Query.sent(token().date(), new Date(Long.MAX_VALUE));
510 else if (s.equals("SENTON")) { Date d = token().date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
511 else if (s.equals("UID")) q = Query.uid(token().set());
515 private static void bad(String s) { throw new Server.Bad(s); }
517 public final byte type;
518 private final String s;
519 private final Token[] l;
521 private static final byte NIL = 0, LIST = 1, QUOTED = 2, NUMBER = 3, ATOM = 4, BAREWORD = 5, SET = 6;
522 public Token() { this.s = null; n = 0; l = null; type = NIL; }
523 public Token(String s) { this(s, false); }
524 public Token(String s, boolean quoted) { this.s = s; n = 0; l = null; type = quoted ? QUOTED : ATOM; }
525 public Token(Token[] list) { this.s = null; n = 0; l = list; type = LIST; }
526 public Token(int number) { this.s = null; n = number; l = null; type = NUMBER; }
528 public String flag() { if (type != ATOM) bad("expected a flag"); return s; }
529 public int n() { if (type != NUMBER) bad("expected number"); return n; }
530 public int nz() { int n = n(); if (n == 0) bad("expected nonzero number"); return n; }
531 public String q() { if (type == NIL) return null; if (type != QUOTED) bad("expected qstring"); return s; }
532 public Token[] l() { if (type == NIL) return null; if (type != LIST) bad("expected list"); return l; }
533 public String nstring() { if (type==NIL) return null; if (type!=QUOTED) bad("expected nstring"); return s; }
534 public String astring() {
535 if (type != ATOM && type != QUOTED) bad("expected atom or string");
536 if (s == null) bad("astring cannot be null");
538 public String[] sl() {
539 if (type == NIL) return null;
540 if (type != LIST) bad("expected list");
541 String[] ret = new String[l.length];
542 for(int i=0; i<ret.length; i++) ret[i] = l[i].s;
546 if (type != LIST) bad("expected flag list");
548 for(int i=0; i<l.length; i++) {
549 String flag = l[i].s;
550 if (flag.equals("\\Deleted")) ret |= Mailbox.Flag.DELETED;
551 else if (flag.equals("\\Seen")) ret |= Mailbox.Flag.SEEN;
552 else if (flag.equals("\\Flagged")) ret |= Mailbox.Flag.FLAGGED;
553 else if (flag.equals("\\Draft")) ret |= Mailbox.Flag.DRAFT;
554 else if (flag.equals("\\Answered")) ret |= Mailbox.Flag.ANSWERED;
555 else if (flag.equals("\\Recent")) ret |= Mailbox.Flag.RECENT;
560 if (type != ATOM) bad("expected a messageid set");
561 Vec.Int ids = new Vec.Int();
562 StringTokenizer st = new StringTokenizer(s, ",");
563 while(st.hasMoreTokens()) {
564 String s = st.nextToken();
565 if (s.indexOf(':') == -1) { ids.addElement(Integer.parseInt(s));ids.addElement(Integer.parseInt(s));continue; }
566 int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
567 String end_s = s.substring(s.indexOf(':')+1);
568 if (end_s.equals("*")) { ids.addElement(start); ids.addElement(Integer.MAX_VALUE); }
570 int end = Integer.parseInt(end_s);
571 for(int j=Math.min(start,end); j<=Math.min(start,end); j++)
578 if (type != QUOTED && type != ATOM) bad("Expected quoted or unquoted date");
579 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
580 } catch (ParseException p) { throw new Server.Bad("invalid date format; " + p); }
582 public Date datetime() {
583 if (type != QUOTED) bad("Expected quoted datetime");
584 try { return new SimpleDateFormat("dd-MM-yyyy hh:mm:ss zzzz").parse(s.trim());
585 } catch (ParseException p) { throw new Server.Bad("invalid datetime format " + s + " : " + p); }
587 public String atom() {
588 if (type != ATOM) bad("expected atom");
589 for(int i=0; i<s.length(); i++) {
590 char c = s.charAt(i);
591 if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*' || c == '\"' | c == '\\')
592 bad("invalid char in atom: " + c);
598 // FIXME: IOException handling
599 public void newline() { try {
600 for(char c = peekc(); c == ' ';) { getc(); c = peekc(); };
601 for(char c = peekc(); c == '\r' || c == '\n';) { getc(); c = peekc(); };
602 } catch (IOException e) { e.printStackTrace(); } }
604 public Token token() { try {
605 Vec toks = new Vec();
606 StringBuffer sb = new StringBuffer();
607 char c = getc(); while (c == ' ') c = getc();
608 if (c == '\r' || c == '\n') bad("unexpected end of line");
610 while(peekc() != '}') sb.append(getc());
611 println("+ Ready when you are...");
612 int octets = Integer.parseInt(sb.toString());
613 while(peekc() == ' ') getc(); // whitespace
614 while (getc() != '\n' && getc() != '\r') { }
615 byte[] bytes = new byte[octets];
617 return new Token(new String(bytes), true);
618 } else if (c == '\"') {
621 if (c == '\\') sb.append(getc());
622 else if (c == '\"') break;
625 return new Token(sb.toString(), true);
627 // NOTE: this is technically a violation of the IMAP grammar, since atoms like FOO[BAR should be legal
628 } else if (c == ']' || c == ')') { return null;
629 } else if (c == '[' || c == '(') {
631 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
632 Token[] ret = new Token[toks.size()];
634 return new Token(ret);
639 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '[' || c == ']' ||
640 c == '{' || c == '\n' || c == '\r')
641 return new Token(sb.toString(), false);
644 } catch (IOException e) { e.printStackTrace(); } return null; }
647 public static class Printer {
648 static String quotify(String s){
649 return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
650 static String quotify(Date d) {
651 return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
652 static String address(Address a) {
653 return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
654 public static String addressList(Object a) {
655 if (a == null) return "NIL";
656 if (a instanceof Address) return "("+address((Address)a)+")";
657 Address[] aa = (Address[])a;
658 StringBuffer ret = new StringBuffer();
660 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
662 return ret.toString();
664 static String flags(Mailbox.Iterator it) {
666 (it.deleted() ? "\\Deleted " : "") +
667 (it.seen() ? "\\Seen " : "") +
668 (it.flagged() ? "\\Flagged " : "") +
669 (it.draft() ? "\\Draft " : "") +
670 (it.answered() ? "\\Answered " : "") +
671 (it.recent() ? "\\Recent " : "");
673 static String flags(int flags) {
675 (((flags & Mailbox.Flag.DELETED) == Mailbox.Flag.DELETED) ? "\\Deleted " : "") +
676 (((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) ? "\\Seen " : "") +
677 (((flags & Mailbox.Flag.FLAGGED) == Mailbox.Flag.FLAGGED) ? "\\Flagged " : "") +
678 (((flags & Mailbox.Flag.DRAFT) == Mailbox.Flag.DRAFT) ? "\\Draft " : "") +
679 (((flags & Mailbox.Flag.ANSWERED) == Mailbox.Flag.ANSWERED)? "\\Answered " : "") +
680 (((flags & Mailbox.Flag.RECENT) == Mailbox.Flag.RECENT) ? "\\Recent " : "");
681 if (ret.endsWith(" ")) ret = ret.substring(0, ret.length() - 1);
684 static String bodystructure(Message m) {
686 return "(\"TEXT\" \"PLAIN\" () NIL NIL \"7BIT\" "+m.rfc822size()+" "+m.lines+")";
688 static String message(Message m) { return m.rfc822(); }
689 static String date(Date d) { return d.toString(); }
690 static String envelope(Message m) {
692 "(" + quotify(m.arrival.toString()) +
693 " " + quotify(m.subject) +
694 " " + addressList(m.from) +
695 " " + addressList(m.headers.get("sender")) +
696 " " + addressList(m.replyto) +
697 " " + addressList(m.to) +
698 " " + addressList(m.cc) +
699 " " + addressList(m.bcc) +
700 " " + quotify((String)m.headers.get("in-reply-to")) +
701 " " + quotify(m.messageid) +
705 public static String qq(String s) {
706 StringBuffer ret = new StringBuffer(s.length() + 20);
708 ret.append(s.length());
713 return ret.toString();
716 private static String join(int[] nums) {
717 StringBuffer ret = new StringBuffer();
718 for(int i=0; i<nums.length; i++) {
720 if (i<nums.length-1) ret.append(' ');
722 return ret.toString();
724 private static String join(String delimit, String[] stuff) {
725 StringBuffer ret = new StringBuffer();
726 for(int i=0; i<stuff.length; i++) {
727 ret.append(stuff[i]);
728 if (i<stuff.length - 1) ret.append(delimit);
730 return ret.toString();
735 // Main //////////////////////////////////////////////////////////////////////////////
737 /** simple listener for testing purposes */
738 public static void main(String[] args) throws Exception {
739 ServerSocket ss = new ServerSocket(143);
741 final Socket s = ss.accept();
742 new Thread() { public void run() { try {
743 final Mailbox root = FileBasedMailbox.getFileBasedMailbox(Mailbox.STORAGE_ROOT+File.separatorChar+"imap", true);
745 new Server.Authenticator() {
746 public Mailbox authenticate(String u, String p) {
747 if (u.equals("megacz")&&p.equals("pass")) return root;
749 } } ).handleRequest();
750 } catch (Exception e) { e.printStackTrace(); } } }.start();