1 package org.ibex.mail.protocol;
3 import org.ibex.crypto.*;
4 import org.ibex.jinetd.Listener;
5 import org.ibex.jinetd.Worker;
6 import org.ibex.mail.*;
7 import org.ibex.util.*;
8 import org.ibex.mail.target.*;
14 // FIXME: this is valid LSUB "" asdfdas%*%*%*%*SFEFGWEF
15 // FIXME: be very careful about where/when we quotify stuff
16 // FIXME: 'UID FOO 100:*' must match at least one message even if all UIDs less than 100
17 // FIXME: LIST should return INBOX if applicable
21 // RFC 3501: IMAPv4 with clarifications
25 // FEATURE: make sure we're being case-insensitive enough; probably want to upcase atom()
26 // FEATURE: MIME-queries and BODYSTRUCTURE
27 // FEATURE: READ-WRITE / READ-ONLY status on SELECT
28 // FEATURE: pipelining
29 // FEATURE: support [charset]
31 // FEATURE: subscriptions
32 // FEATURE: tune for efficiency
34 // FEATURE: asynchronous client notifications (need to re-read RFC)
39 public static final float version = (float)0.2;
41 // API Class //////////////////////////////////////////////////////////////////////////////
43 public static interface Client {
44 public void expunge(int uid);
45 public void list(char separator, String mailbox, boolean lsub, boolean phantom);
46 public void fetch(int num, int flags, int size, Message m, int muid); // m may be null or incomplete
49 public static interface Server {
50 public String[] capability();
51 public Hashtable id(Hashtable clientId);
52 public void copy(Query q, String to);
53 public void login(String u, String p);
55 public void unselect();
56 public void delete(String m);
57 public void create(String m);
58 public void append(String m, int flags, Date arrival, String body);
62 public void subscribe(String mailbox);
63 public void unsubscribe(String mailbox);
64 public int unseen(String mailbox);
65 public int recent(String mailbox);
66 public int count(String mailbox);
67 public int uidNext(String mailbox);
68 public int uidValidity(String mailbox);
69 public int[] search(Query q, boolean uid);
70 public void rename(String from, String to);
71 public void select(String mailbox, boolean examineOnly);
72 public void setFlags(Query q, int flags, boolean uid, boolean silent);
73 public void removeFlags(Query q, int flags, boolean uid, boolean silent);
74 public void addFlags(Query q, int flags, boolean uid, boolean silent);
75 public void expunge();
76 public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid);
77 public void lsub(String start, String ref);
78 public void list(String start, String ref);
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; }
99 public MailboxWrapper(Login auth, Client c) { this.auth=auth; this.client=c;}
101 private Mailbox mailbox(String name, boolean create) { return mailbox(name, create, true); }
102 private Mailbox mailbox(String name, boolean create, boolean throwexn) {
103 if (name.equalsIgnoreCase("inbox")) return inbox;
105 for(StringTokenizer st = new StringTokenizer(name, sep + ""); st.hasMoreTokens();)
106 if ((m = m.slash(st.nextToken(), create)) == null) {
107 if (throwexn) throw new Server.No("no such mailbox " + name);
113 // FEATURE: not accurate when a wildcard and subsequent non-wildcards both match a single component
114 public void lsub(String start, String ref) { list(start, ref, true); }
115 public void list(String start, String ref) { list(start, ref, false); }
116 public void list(String start, String ref, boolean lsub) {
117 if (ref.length() == 0) { client.list(sep, start, lsub, false); return; }
118 while (start.endsWith(""+sep)) start = start.substring(0, start.length() - 1);
119 if (ref.endsWith("%")) ref = ref + sep;
120 String[] children = (start.length() == 0 ? root : mailbox(start, false)).children();
121 for(int i=0; i<children.length; i++) {
122 String s = children[i], pre = ref, kid = start + (start.length() > 0 ? sep+"" : "") + s;
123 boolean phantom = mailbox(kid, false).phantom();
125 if (pre.length() == 0) {
126 if (s.length() == 0) client.list(sep, kid, lsub, phantom);
127 } else switch(pre.charAt(0)) {
128 case sep: if (s.length() == 0) list(kid, pre.substring(1), lsub); break;
129 case '%': client.list(sep,kid,lsub,phantom);pre=pre.substring(1); s = ""; continue;
130 case '*': client.list(sep,kid,lsub,phantom);list(kid,pre,lsub);pre=pre.substring(1); break;
131 default: if (s.length()==0) break;
132 if (s.charAt(0) != pre.charAt(0)) break;
133 s = s.substring(1); pre = pre.substring(1); continue;
140 public String[] capability() { return new String[] { "IMAP4rev1" , "UNSELECT", "ID" }; }
141 public Hashtable id(Hashtable clientId) {
142 Hashtable response = new Hashtable();
143 response.put("name", IMAP.class.getName());
144 response.put("version", version + "");
145 response.put("os", System.getProperty("os.name", null));
146 response.put("os-version", System.getProperty("os.version", null));
147 response.put("vendor", "none");
148 response.put("support-url", "http://mail.ibex.org/");
152 public void copy(Query q, String to) { copy(q, mailbox(to, false)); }
153 /* */ void copy(Query q, Mailbox to) {
154 for(Mailbox.Iterator it=selected().iterator(q);it.next();) to.add(it.cur(), it.flags() | Mailbox.Flag.RECENT); }
156 public void login(String u, String p) {
157 Account account = null;
158 if ((account = auth.login(u,p)) == null) throw new No("Login failed.");
159 root = account.getMailbox(IMAP.class);
160 inbox = mailbox("INBOX", false); // FEATURE: ??
162 public void unselect() { selected = null; }
163 public void delete(String m0) { delete(mailbox(m0,false)); }
164 public void delete(Mailbox m) { if (!m.equals(inbox)) m.destroy(false); else throw new Bad("can't delete inbox"); }
165 public void create(String m) { mailbox(m, true, false); }
166 public void append(String m,int f,Date a,String b) { try {
167 mailbox(m,false).add(new Message(new Stream(b), new Message.Envelope(null,null,a)),f|Mailbox.Flag.RECENT);
168 } catch (Message.Malformed e) { throw new No(e.getMessage()); } }
169 public void check() { }
170 public void noop() { }
171 public void logout() { }
172 public void close() { for(Mailbox.Iterator it=selected().iterator(Query.deleted()); it.next();) it.delete(); }
173 public void expunge() { for(Mailbox.Iterator it = selected().iterator(Query.deleted());it.next();) expunge(it); }
174 public void expunge(Mailbox.Iterator it) { client.expunge(it.uid()); it.delete(); }
175 public void subscribe(String mailbox) { }
176 public void unsubscribe(String mailbox) { }
177 public int unseen(String mailbox) { return mailbox(mailbox, false).count(Query.not(Query.seen())); }
178 public int recent(String mailbox) { return mailbox(mailbox, false).count(Query.recent()); }
179 public int count(String mailbox) { return mailbox(mailbox, false).count(Query.all()); }
180 public int uidNext(String mailbox) { return mailbox(mailbox, false).uidNext(); }
181 public int uidValidity(String mailbox) { return mailbox(mailbox, false).uidValidity(); }
182 public void select(String mailbox, boolean examineOnly) {
183 selected = mailbox(mailbox, false);
186 public int[] search(Query q, boolean uid) {
187 Vec.Int vec = new Vec.Int();
188 for(Mailbox.Iterator it = selected().iterator(q); it.next();) {
189 vec.addElement(uid ? it.uid() : it.num());
195 public void setFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, 0, silent); }
196 public void addFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, 1, silent); }
197 public void removeFlags(Query q, int f, boolean uid, boolean silent) { doFlags(q, f, uid, -1, silent); }
199 private void doFlags(Query q, int flags, boolean uid, int style, boolean silent) {
200 for(Mailbox.Iterator it = selected().iterator(q);it.next();) {
201 boolean recent = it.recent();
202 if (style == -1) it.removeFlags(flags);
203 else if (style == 0) it.setFlags(flags);
204 else if (style == 1) it.addFlags(flags);
207 //if (!silent) client.fetch(it.num(), it.flags(), -1, null, it.uid());
210 public void rename(String from0, String to) {
211 Mailbox from = mailbox(from0, false);
212 if (from.equals(inbox)) { from.copy(Query.all(), mailbox(to, true)); }
213 else if (to.equalsIgnoreCase("inbox")) { from.copy(Query.all(), mailbox(to, true)); from.destroy(false); }
214 else from.rename(to);
216 public void fetch(Query q, int spec, String[] headers, int start, int end, boolean uid) {
217 for(Mailbox.Iterator it = selected().iterator(q); it.next(); ) {
218 Message message = ((spec & (BODYSTRUCTURE | ENVELOPE | INTERNALDATE | FIELDS | FIELDSNOT | RFC822 |
219 RFC822TEXT | RFC822SIZE | HEADERNOT | HEADER)) != 0) ? it.cur() : null;
220 int size = message == null ? 0 : message.size();
221 client.fetch(it.num(), it.flags(), size, message, it.uid());
228 // Single Session Handler //////////////////////////////////////////////////////////////////////////////
230 /** takes an IMAP.Server and exposes it to the world as an IMAP server on a TCP socket */
231 public static class Listener implements Worker, Client {
232 String selectedName = null;
233 Mailbox inbox = null, root = null;
236 Parser parser = null;
237 Connection conn = null;
238 public Listener(Login auth) { this.auth = auth; }
239 Parser.Token token() { return parser.token(); }
240 void println(String s) { conn.println(s); }
241 void newline() { parser.newline(); }
242 Query query() { return parser.query(); }
243 public void handleRequest(Connection conn) {
245 parser = new Parser(conn);
246 api = new IMAP.MailboxWrapper(auth, this);
247 conn.setTimeout(30 * 60 * 1000);
248 println("* OK " + conn.vhost + " " + IMAP.class.getName() + " IMAP4rev1 [RFC3501] v" + version + " server ready");
249 for(String tag = null;; newline()) try {
252 tag = null; Parser.Token tok = token(); if (tok == null) return; tag = tok.astring();
253 String command = token().atom();
254 if (command.equalsIgnoreCase("UID")) { uid = true; command = token().atom(); }
255 int commandKey = ((Integer)commands.get(command.toUpperCase())).intValue();
257 case LOGIN: api.login(token().astring(), token().astring()); break;
258 case CAPABILITY: println("* CAPABILITY " + Printer.join(" ", api.capability())); break;
259 case AUTHENTICATE: throw new Server.No("AUTHENTICATE not supported");
260 case LOGOUT: api.logout(); println("* BYE"); conn.close(); return;
261 case LIST: api.list(token().q(), token().q()); break;
262 case LSUB: api.lsub(token().q(), token().q()); break;
263 case SUBSCRIBE: api.subscribe(token().astring()); break;
264 case UNSUBSCRIBE: api.unsubscribe(token().astring()); break;
265 case RENAME: api.rename(token().astring(), token().astring()); break;
266 case COPY: selected(); api.copy(Query.set(uid, token().set()), token().astring()); break;
267 case DELETE: api.delete(token().atom()); break;
268 case CHECK: selected(); api.check(); break;
269 case NOOP: api.noop(); break;
270 case CLOSE: selected(); api.close(); break;
271 case EXPUNGE: selected(); api.expunge(); break;
272 case UNSELECT: selected(); api.unselect(); selected = false; break;
273 case CREATE: api.create(token().astring()); break;
274 case FETCH: selected(); fetch(Query.set(lastuid=uid, token().set()),
275 lastfetch=token().lx(), 0, 0, 0, uid, 0); break;
276 case SEARCH: selected(); println("* SEARCH " + Printer.join(api.search(query(), uid))); break;
279 String mailbox = token().astring();
280 api.select(mailbox, commandKey==EXAMINE);
281 println("* FLAGS (\\Answered \\Flagged \\Deleted \\Seen \\Draft)");
282 println("* " + api.count(mailbox) + " EXISTS");
283 println("* " + api.recent(mailbox) + " RECENT");
284 println("* OK [UIDVALIDITY " + api.uidValidity(mailbox) + "] UIDs valid");
285 println("* OK [UIDNEXT " + api.uidNext(mailbox) + "]");
286 println("* OK [PERMANENTFLAGS (\\Seen \\Draft \\Answered \\Deleted)]");
290 String mailbox = token().astring(); // hack for GNUS buggy client
291 Parser.Token[] list = token().l();
292 String response = "";
293 for(int i=0; i<list.length; i++) {
294 String s = list[i].atom().toUpperCase();
295 if (i>0) response += " ";
296 if (s.equals("MESSAGES")) response += "MESSAGES " + api.count(mailbox);
297 if (s.equals("RECENT")) response += "RECENT " + api.recent(mailbox);
298 if (s.equals("UIDNEXT")) response += "UIDNEXT " + api.uidNext(mailbox);
299 if (s.equals("UIDVALIDITY")) response += "UIDVALIDITY " + api.uidValidity(mailbox);
300 if (s.equals("UNSEEN")) response += "UNSEEN " + api.unseen(mailbox);
302 println("* STATUS " + mailbox + " (" + response + ")");
306 String m = token().astring();
308 Date arrival = new Date();
309 Parser.Token t = token();
310 if (t.type == t.LIST) { flags = t.flags(); t = token(); }
311 if (t.type != t.QUOTED) { arrival = t.datetime(); t = token(); }
312 api.append(m, flags, arrival, t.q());
316 Query q = uid ? Query.uid(token().set()) : Query.num(token().set());
317 String s = token().atom().toUpperCase();
318 int flags = token().flags();
319 if (s.equals("FLAGS")) api.setFlags(q, flags, uid, false);
320 else if (s.equals("+FLAGS")) api.addFlags(q, flags, uid, false);
321 else if (s.equals("-FLAGS")) api.removeFlags(q, flags, uid, false);
322 else if (s.equals("FLAGS.SILENT")) api.setFlags(q, flags, uid, true);
323 else if (s.equals("+FLAGS.SILENT")) api.addFlags(q, flags, uid, true);
324 else if (s.equals("-FLAGS.SILENT")) api.removeFlags(q, flags, uid, true);
325 else throw new Server.Bad("unknown STORE specifier " + s);
327 default: throw new Server.Bad("unrecognized command \"" + command + "\"");
329 println(tag+" OK "+command+" Completed. " +
330 (commandKey == LOGIN ? ("[CAPABILITY "+Printer.join(" ", api.capability())+"]") : ""));
331 } catch (Server.Bad b) { println(tag==null ? "* BAD Invalid tag":(tag + " Bad " + b.toString())); Log.warn(this,b);
332 } catch (Server.No n) { println(tag==null?"* BAD Invalid tag":(tag+" No " + n.toString())); Log.warn(this,n); }
335 private Parser.Token[] lastfetch = null; // hack
336 private boolean lastuid = false; // hack
337 private boolean selected = false;
338 private void selected() { if (!selected) throw new Server.Bad("no mailbox selected"); }
340 // Callbacks //////////////////////////////////////////////////////////////////////////////
342 public void expunge(int uid) { println("* " + uid + " EXPUNGE"); }
343 public void fetch(int n, int f, int size, Message m, int muid) { fetch(m, lastfetch, n, f, size, lastuid, muid); }
344 public void list(char sep, String mb, boolean sub, boolean p) {
345 println("* " + (sub?"LSUB":"LIST")+" ("+(p?"\\Noselect":"")+") \""+sep+"\" \""+mb+"\"");}
348 * Parse a fetch request <i>or</i> emit a fetch reply.
350 * To avoid duplicating tedious parsing logic, this function
351 * performs both of the following tasks:
352 * - parse the fetch request in Token[] t and return a fetch spec
353 * - emit a fetch reply for the parsed spec with respect to message m
355 private void fetch(Object o, Parser.Token[] t, int num, int flags, int size, boolean uid, int muid) {
356 Query q = o instanceof Query ? (Query)o : null;
357 Message m = o instanceof Message ? (Message)o : null;
358 boolean e = q == null;
361 int spec = 0; // spec; see constants for flags
362 String[] headers = null;
363 int start = -1, end = -1;
364 StringBuffer r = new StringBuffer();
365 if (e) { r.append(uid ? muid : num); r.append(" FETCH ("); }
366 int initlen = r.length();
368 boolean good = false;
369 for(int i=0; i<t.length; i++)
370 if ((t[i].type == Parser.Token.QUOTED || t[i].type == Parser.Token.ATOM) &&
371 t[i].astring().equalsIgnoreCase("UID")) good = true;
373 Parser.Token[] t2 = new Parser.Token[t.length + 1];
374 System.arraycopy(t, 0, t2, 0, t.length);
375 t2[t2.length - 1] = parser.token("UID");
376 lastfetch = (t = t2);
379 if (t.length == 0 && (t[0].type == Parser.Token.QUOTED || t[0].type == Parser.Token.ATOM)) {
380 if (t[0].astring().equalsIgnoreCase("ALL"))
381 t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"),
382 parser.token("ENVELOPE"), parser.token("RFC822.SIZE") };
383 else if (t[0].astring().equalsIgnoreCase("FULL"))
384 t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"), parser.token("BODY"),
385 parser.token("ENVELOPE"), parser.token("RFC822.SIZE") };
386 else if (t[0].astring().equalsIgnoreCase("FAST"))
387 t = new Parser.Token[] { parser.token("FLAGS"), parser.token("INTERNALDATE"),
388 parser.token("RFC822.SIZE") };
390 for(int i=0; i<t.length; i++) {
391 if (r.length() > initlen) r.append(" ");
392 if (t[i] == null || t[i].s == null) continue;
393 String s = t[i].s.toUpperCase();
394 r.append(s.equalsIgnoreCase("BODY.PEEK")?"BODY":s);
395 if (s.equals("BODYSTRUCTURE")) { spec|=BODYSTRUCTURE;if(e){r.append(" ");r.append(Printer.bodystructure(m));}
396 } else if (s.equals("ENVELOPE")) { spec|=ENVELOPE; if(e){r.append(" ");r.append(Printer.envelope(m));}
397 } else if (s.equals("FLAGS")) { spec|=FLAGS; if(e){r.append(" ");r.append(Printer.flags(flags));}
398 } else if (s.equals("INTERNALDATE")) { spec|=INTERNALDATE; if(e){r.append(" ");r.append(Printer.date(m.envelope.arrival));}
399 } else if (s.equals("RFC822")) { spec|=RFC822; if(e){r.append(" ");r.append(Printer.message(m));}
400 } else if (s.equals("RFC822.TEXT")) { spec|=RFC822TEXT; if(e){r.append(" ");r.append(Printer.qq(m.body));}
401 } else if (s.equals("RFC822.HEADER")){ spec|=HEADER;if(e){r.append(" ");r.append(Printer.qq(m.headers.raw+"\r\n"));}
402 } else if (s.equals("RFC822.SIZE")) { spec|=RFC822SIZE; if(e){r.append(" ");r.append(m.size());}
403 } else if (s.equals("UID")) { spec|=UID; if(e){r.append(" ");r.append(muid); }
404 } else if (!(s.equals("BODY.PEEK") || s.equals("BODY"))) { throw new Server.No("unknown fetch argument: " + s);
406 if (s.equalsIgnoreCase("BODY.PEEK")) spec |= PEEK;
407 //else if (e) api.addFlags(Query.num(new int[] { num, num }), Mailbox.Flag.SEEN, false, false);
408 if (i >= t.length - 1 || t[i+1].type != Parser.Token.LIST) {
409 spec |= BODYSTRUCTURE;
410 if (e) { r.append(" "); r.append(Printer.bodystructure(m)); } continue;
411 //{ if (e) { r.append(" "); r.append(Printer.qq(m.body)); } continue; }
415 Parser.Token[] list = t[++i].l();
416 s = list.length == 0 ? "" : list[0].s.toUpperCase();
418 if (list.length == 0) { spec |= RFC822TEXT; if(e) payload = m.headers.raw+"\r\n"+m.body; }
419 else if (s.equals("")) { spec |= RFC822TEXT; if(e) payload = m.headers.raw+"\r\n"+m.body; }
420 else if (s.equals("TEXT")) { spec |= RFC822TEXT; if(e) payload = m.body; }
421 else if (s.equals("HEADER")) { spec |= HEADER; if(e) payload = m.headers.raw+"\r\n"; }
422 else if (s.equals("HEADER.FIELDS")) { spec |= FIELDS; payload=headers(r,t[i].l()[1].sl(),false,m,e); }
423 else if (s.equals("HEADER.FIELDS.NOT")) { spec |= FIELDSNOT; payload=headers(r,t[i].l()[1].sl(),true,m,e); }
424 else if (s.equals("MIME")) { throw new Server.Bad("MIME not supported"); }
425 else throw new Server.Bad("unknown section type " + s);
426 if (i<t.length - 1 && (t[i+1].s != null && t[i+1].s.startsWith("<"))) {
428 s = t[i].s.substring(1, t[i].s.indexOf('>'));
429 int dot = s.indexOf('.');
430 start = dot == -1 ? Integer.parseInt(s) : Integer.parseInt(s.substring(0, s.indexOf('.')));
431 end = dot == -1 ? -1 : Integer.parseInt(s.substring(s.indexOf('.') + 1));
432 if (e) { payload = payload.substring(start, Math.min(end+1,payload.length())); r.append("<"+start+">"); }
434 if (e) { r.append("] "); r.append(Printer.qq(payload)); }
439 println("* " + r.toString());
441 api.fetch(q, spec, headers, start, end, uid);
445 private String headers(StringBuffer r, String[] headers, boolean negate, Message m, boolean e) {
447 if (e) r.append(" (");
449 if(e) for(int j=0; j<headers.length; j++) {
450 r.append(headers[j] + (j<headers.length-1?" ":""));
451 if (m.headers.gets(headers[j]) != null) payload += headers[j]+": "+m.headers.gets(headers[j])+"\r\n";
454 throw new Server.No("HEADERS.NOT temporarily disaled");
456 if (e) for(int j=0; j<headers.length; j++) r.append(headers[j] + (j<headers.length-1?" ":""));
457 if(e) { OUTER: for(Enumeration x=m.headers.keys(); x.hasMoreElements();) {
458 String key = (String)x.nextElement();
459 for(int j=0; j<headers.length; j++) if (key.equalsIgnoreCase(headers[j])) continue OUTER;
460 payload += key + ": " + m.headers.gets(key)+"\r\n";
464 if (e) r.append(")");
465 return payload + "\r\n";
468 private static final Hashtable commands = new Hashtable();
469 private static final int UID = 0; static { commands.put("UID", new Integer(UID)); }
470 private static final int AUTHENTICATE = 1; static { commands.put("AUTHENTICATE", new Integer(AUTHENTICATE)); }
471 private static final int LIST = 2; static { commands.put("LIST", new Integer(LIST)); }
472 private static final int LSUB = 3; static { commands.put("LSUB", new Integer(LSUB)); }
473 private static final int SUBSCRIBE = 4; static { commands.put("SUBSCRIBE", new Integer(SUBSCRIBE)); }
474 private static final int UNSUBSCRIBE = 5; static { commands.put("UNSUBSCRIBE", new Integer(UNSUBSCRIBE)); }
475 private static final int CAPABILITY = 6; static { commands.put("CAPABILITY", new Integer(CAPABILITY)); }
476 private static final int ID = 7; static { commands.put("ID", new Integer(ID)); }
477 private static final int LOGIN = 8; static { commands.put("LOGIN", new Integer(LOGIN)); }
478 private static final int LOGOUT = 9; static { commands.put("LOGOUT", new Integer(LOGOUT)); }
479 private static final int RENAME = 10; static { commands.put("RENAME", new Integer(RENAME)); }
480 private static final int EXAMINE = 11; static { commands.put("EXAMINE", new Integer(EXAMINE)); }
481 private static final int SELECT = 12; static { commands.put("SELECT", new Integer(SELECT)); }
482 private static final int COPY = 13; static { commands.put("COPY", new Integer(COPY)); }
483 private static final int DELETE = 14; static { commands.put("DELETE", new Integer(DELETE)); }
484 private static final int CHECK = 15; static { commands.put("CHECK", new Integer(CHECK)); }
485 private static final int NOOP = 16; static { commands.put("NOOP", new Integer(NOOP)); }
486 private static final int CLOSE = 17; static { commands.put("CLOSE", new Integer(CLOSE)); }
487 private static final int EXPUNGE = 18; static { commands.put("EXPUNGE", new Integer(EXPUNGE)); }
488 private static final int UNSELECT = 19; static { commands.put("UNSELECT", new Integer(UNSELECT)); }
489 private static final int CREATE = 20; static { commands.put("CREATE", new Integer(CREATE)); }
490 private static final int STATUS = 21; static { commands.put("STATUS", new Integer(STATUS)); }
491 private static final int FETCH = 22; static { commands.put("FETCH", new Integer(FETCH)); }
492 private static final int APPEND = 23; static { commands.put("APPEND", new Integer(APPEND)); }
493 private static final int STORE = 24; static { commands.put("STORE", new Integer(STORE)); }
494 private static final int SEARCH = 25; static { commands.put("SEARCH", new Integer(SEARCH)); }
497 public static class Parser {
498 private Stream stream;
499 public Parser(Stream from) { this.stream = from; }
500 public Token token(String s) { return new Token(s); }
501 protected Query query() {
506 Parser.Token t = token(false);
507 if (t == null) break;
508 if (t.type == t.LIST) throw new Server.No("nested queries not yet supported FIXME");
509 else if (t.type == t.SET) return Query.num(t.set());
510 s = t.atom().toUpperCase();
511 if (s.equals("NOT")) { not = true; continue; }
512 if (s.equals("OR")) return Query.or(query(), query()); // FIXME parse rest of list
513 if (s.equals("AND")) return Query.and(query(), query());
515 if (s.startsWith("UN")) { not = true; s = s.substring(2); }
516 if (s.equals("ANSWERED")) q = Query.answered();
517 else if (s.equals("DELETED")) q = Query.deleted();
518 else if (s.equals("ALL")) q = Query.all();
519 else if (s.equals("DRAFT")) q = Query.draft();
520 else if (s.equals("FLAGGED")) q = Query.flagged();
521 else if (s.equals("RECENT")) q = Query.recent();
522 else if (s.equals("SEEN")) q = Query.seen();
523 else if (s.equals("OLD")) { not = true; q = Query.recent(); }
524 else if (s.equals("NEW")) q = Query.and(Query.recent(), Query.not(Query.seen()));
525 else if (s.equals("KEYWORD")) q = Query.header("keyword", token().flag());
526 else if (s.equals("HEADER")) q = Query.header(token().astring(), token().astring());
527 else if (s.equals("BCC")) q = Query.header("bcc", token().astring());
528 else if (s.equals("CC")) q = Query.header("cc", token().astring());
529 else if (s.equals("FROM")) q = Query.header("from", token().astring());
530 else if (s.equals("TO")) q = Query.header("to", token().astring());
531 else if (s.equals("SUBJECT")) q = Query.header("subject", token().astring());
532 else if (s.equals("LARGER")) q = Query.size(token().n(), Integer.MAX_VALUE);
533 else if (s.equals("SMALLER")) q = Query.size(Integer.MIN_VALUE, token().n());
534 else if (s.equals("BODY")) q = Query.body(token().astring());
535 else if (s.equals("TEXT")) q = Query.full(token().astring());
536 else if (s.equals("BEFORE")) q = Query.arrival(new Date(0), token().date());
537 else if (s.equals("SINCE")) q = Query.arrival(token().date(), new Date(Long.MAX_VALUE));
538 else if (s.equals("ON")) { Date d = token().date(); q = Query.arrival(d, new Date(d.getTime() + 24 * 60 * 60)); }
539 else if (s.equals("SENTBEFORE")) q = Query.sent(new Date(0), token().date());
540 else if (s.equals("SENTSINCE")) q = Query.sent(token().date(), new Date(Long.MAX_VALUE));
541 else if (s.equals("SENTON")) { Date d = token().date(); q = Query.sent(d, new Date(d.getTime() + 24 * 60 * 60)); }
542 else if (s.equals("UID")) q = Query.uid(token().set());
546 private static void bad(String s) { throw new Server.Bad(s); }
548 public final byte type;
549 private final String s;
550 private final Parser.Token[] l;
552 private static final byte NIL = 0, LIST = 1, QUOTED = 2, NUMBER = 3, ATOM = 4, BAREWORD = 5, SET = 6;
553 public Token() { this.s = null; n = 0; l = null; type = NIL; }
554 public Token(String s) { this(s, false); }
555 public Token(String s, boolean quoted) { this.s = s; n = 0; l = null; type = quoted ? QUOTED : ATOM; }
556 public Token(Parser.Token[] list) { this.s = null; n = 0; l = list; type = LIST; }
557 public Token(int number) { this.s = null; n = number; l = null; type = NUMBER; }
559 public String flag() { if (type != ATOM) bad("expected a flag"); return s; }
560 public int n() { if (type != NUMBER) bad("expected number"); return n; }
561 public int nz() { int n = n(); if (n == 0) bad("expected nonzero number"); return n; }
562 public String q() { if (type == NIL) return null; if (type != QUOTED) bad("expected qstring"); return s; }
563 public Parser.Token[] l() { if (type == NIL) return null; if (type != LIST) bad("expected list"); return l; }
564 public Parser.Token[] lx() {
565 if (type == LIST) return l;
569 Parser.Token t = token(false);
570 if (t == null) break;
573 Parser.Token[] ret = new Parser.Token[v.size()];
577 public String nstring() { if (type==NIL) return null; if (type!=QUOTED) bad("expected nstring"); return s; }
578 public String astring() {
579 if (type != ATOM && type != QUOTED) bad("expected atom or string");
580 if (s == null) bad("astring cannot be null");
582 public String[] sl() {
583 if (type == NIL) return null;
584 if (type != LIST) bad("expected list");
585 String[] ret = new String[l.length];
586 for(int i=0; i<ret.length; i++) ret[i] = l[i].s;
590 if (type != LIST) bad("expected flag list");
592 for(int i=0; i<l.length; i++) {
593 String flag = l[i].s;
594 if (flag.equals("\\Deleted")) ret |= Mailbox.Flag.DELETED;
595 else if (flag.equals("\\Seen")) ret |= Mailbox.Flag.SEEN;
596 else if (flag.equals("\\Flagged")) ret |= Mailbox.Flag.FLAGGED;
597 else if (flag.equals("\\Draft")) ret |= Mailbox.Flag.DRAFT;
598 else if (flag.equals("\\Answered")) ret |= Mailbox.Flag.ANSWERED;
599 else if (flag.equals("\\Recent")) ret |= Mailbox.Flag.RECENT;
604 if (type != ATOM) bad("expected a messageid set");
605 Vec.Int ids = new Vec.Int();
606 StringTokenizer st = new StringTokenizer(s, ",");
607 while(st.hasMoreTokens()) {
608 String s = st.nextToken();
609 if (s.indexOf(':') == -1) {
612 ids.addElement(Integer.MAX_VALUE);
614 ids.addElement(Integer.parseInt(s));
615 ids.addElement(Integer.parseInt(s));
618 int start = Integer.parseInt(s.substring(0, s.indexOf(':')));
619 String end_s = s.substring(s.indexOf(':')+1);
620 if (end_s.equals("*")) { ids.addElement(start); ids.addElement(Integer.MAX_VALUE); }
622 int end = Integer.parseInt(end_s);
623 for(int j=Math.min(start,end); j<=Math.max(start,end); j++) {
632 if (type != QUOTED && type != ATOM) bad("Expected quoted or unquoted date");
633 try { return new SimpleDateFormat("dd-MMM-yyyy").parse(s);
634 } catch (ParseException p) { throw new Server.Bad("invalid date format; " + p); }
636 public Date datetime() {
637 if (type != QUOTED) bad("Expected quoted datetime");
638 try { return new SimpleDateFormat("dd-MM-yyyy hh:mm:ss zzzz").parse(s.trim());
639 } catch (ParseException p) { throw new Server.Bad("invalid datetime format " + s + " : " + p); }
641 public String atom() {
642 if (type != ATOM) bad("expected atom");
643 for(int i=0; i<s.length(); i++) {
644 char c = s.charAt(i);
645 if (c == '(' || c == ')' || c == '{' || c == ' ' || c == '%' || c == '*' || c == '\"' | c == '\\')
646 bad("invalid char in atom: " + c);
652 public void newline() {
653 while (stream.peekc() == '\r' || stream.peekc() == '\n' || stream.peekc() == ' ') {
654 for(char c = stream.peekc(); c == ' ';) { stream.getc(); c = stream.peekc(); };
655 for(char c = stream.peekc(); c == '\r' || c == '\n';) { stream.getc(); c = stream.peekc(); };
659 public Token token() { return token(true); }
660 public Token token(boolean freak) {
661 Vec toks = new Vec();
662 StringBuffer sb = new StringBuffer();
663 char c = stream.getc(); while (c == ' ') c = stream.getc();
664 if (c == '\r' || c == '\n') { if (freak) bad("unexpected end of line"); return null; }
666 while(stream.peekc() != '}') sb.append(stream.getc());
668 stream.println("+ Ready when you are...");
669 int octets = Integer.parseInt(sb.toString());
670 while(stream.peekc() == ' ') stream.getc(); // whitespace
671 while(stream.peekc() == '\n' || stream.peekc() == '\r') stream.getc();
672 byte[] bytes = new byte[octets];
674 while(numread < bytes.length) {
675 int n = stream.read(bytes, numread, bytes.length - numread);
676 if (n == -1) bad("end of stream while reading IMAP qstring");
679 return new Token(new String(bytes), true);
680 } else if (c == '\"') {
683 if (c == '\\') sb.append(stream.getc());
684 else if (c == '\"') break;
687 return new Token(sb.toString(), true);
689 // NOTE: this is technically a violation of the IMAP grammar, since atoms like FOO[BAR should be legal
690 } else if (c == ']' || c == ')') { return null;
691 } else if (c == '[' || c == '(') {
693 do { t = token(); if (t != null) toks.addElement(t); } while (t != null);
694 Token[] ret = new Token[toks.size()];
696 return new Token(ret);
701 if (c == ' ' || c == '\"' || c == '(' || c == ')' || c == '[' || c == ']' ||
702 c == '{' || c == '\n' || c == '\r')
703 return new Token(sb.toString(), false);
709 public static class Printer {
710 static String quotify(String s){
711 return s==null?"NIL":"\""+s.replaceAll("\\\\","\\\\").replaceAll("\"","\\\\\"")+"\"";}
712 static String quotify(Date d) {
713 return new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss +zzzz").format(d); }
714 static String address(Address a) {
715 return"("+quotify(a.description)+" NIL "+quotify(a.user)+" "+quotify(a.host)+")"; }
716 public static String addressList(Object a) {
717 if (a == null) return "NIL";
718 if (a instanceof Address) return "("+address((Address)a)+")";
719 if (a instanceof String) return "("+address(Address.parse((String)a))+")";
720 Address[] aa = (Address[])a;
721 StringBuffer ret = new StringBuffer();
723 for(int i=0; i<aa.length; i++) { ret.append(aa[i]); if (i < aa.length - 1) ret.append(" "); }
725 return ret.toString();
727 static String flags(Mailbox.Iterator it) {
729 (it.deleted() ? "\\Deleted " : "") +
730 (it.seen() ? "\\Seen " : "") +
731 (it.flagged() ? "\\Flagged " : "") +
732 (it.draft() ? "\\Draft " : "") +
733 (it.answered() ? "\\Answered " : "") +
734 (it.recent() ? "\\Recent " : "");
736 static String flags(int flags) {
738 (((flags & Mailbox.Flag.DELETED) == Mailbox.Flag.DELETED) ? "\\Deleted " : "") +
739 (((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) ? "\\Seen " : "") +
740 (((flags & Mailbox.Flag.FLAGGED) == Mailbox.Flag.FLAGGED) ? "\\Flagged " : "") +
741 (((flags & Mailbox.Flag.DRAFT) == Mailbox.Flag.DRAFT) ? "\\Draft " : "") +
742 (((flags & Mailbox.Flag.ANSWERED) == Mailbox.Flag.ANSWERED)? "\\Answered " : "") +
743 (((flags & Mailbox.Flag.RECENT) == Mailbox.Flag.RECENT) ? "\\Recent " : "");
744 if (ret.endsWith(" ")) ret = ret.substring(0, ret.length() - 1);
747 static String bodystructure(Message m) {
749 return "(\"TEXT\" \"PLAIN\" (\"CHARSET\" \"ISO-8859-1\") NIL NIL \"7BIT\" "+m.size()+" "+m.lines+")";
751 static String message(Message m) { return m.toString(); }
752 static String date(Date d) { return d.toString(); }
753 static String envelope(Message m) {
755 "(" + quotify(m.envelope.arrival.toString()) +
756 " " + quotify(m.subject) +
757 " " + addressList(m.from) +
758 " " + addressList(m.headers.gets("sender")) +
759 " " + addressList(m.replyto) +
760 " " + addressList(m.to) +
761 " " + addressList(m.cc) +
762 " " + addressList(m.bcc) +
763 " " + quotify((String)m.headers.gets("in-reply-to")) +
764 " " + quotify(m.messageid) +
768 public static String qq(String s) {
769 StringBuffer ret = new StringBuffer();
771 ret.append(s.length());
776 return ret.toString();
779 private static String join(int[] nums) {
780 StringBuffer ret = new StringBuffer();
781 for(int i=0; i<nums.length; i++) {
783 if (i<nums.length-1) ret.append(' ');
785 return ret.toString();
787 private static String join(String delimit, String[] stuff) {
788 StringBuffer ret = new StringBuffer();
789 for(int i=0; i<stuff.length; i++) {
790 ret.append(stuff[i]);
791 if (i<stuff.length - 1) ret.append(delimit);
793 return ret.toString();
798 // Main //////////////////////////////////////////////////////////////////////////////
800 public static final int
801 PEEK=0x1, BODYSTRUCTURE=0x2, ENVELOPE=0x4, FLAGS=0x8, INTERNALDATE=0x10, FIELDS=0x800, FIELDSNOT=0x1000,
802 RFC822=0x20, RFC822TEXT=0x40, RFC822SIZE=0x80, HEADERNOT=0x100, UID=0x200, HEADER=0x400;