1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
6 import org.prevayler.*;
7 import org.ibex.mail.*;
8 import org.ibex.util.*;
12 import java.nio.channels.*;
16 import javax.servlet.*;
17 import javax.servlet.http.*;
19 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
20 public class FileBasedMailbox extends Mailbox.Default {
22 public static final long MAGIC_DATE = 0;
23 private static final char slash = File.separatorChar;
24 private static final WeakHashMap<String,Mailbox> instances = new WeakHashMap<String,Mailbox>();
25 public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
26 public Mailbox slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
28 // FIXME: should be a File()
29 public static synchronized Mailbox getFileBasedMailbox(String path, boolean create) {
31 Mailbox ret = instances.get(path);
33 if (!create && !(new File(path).exists())) return null;
34 if (new File(new File(path)+"/subscribers").exists()) {
35 ret = new MailingList(new File(path), new FileBasedMailbox(new File(path)));
37 ret = new FileBasedMailbox(new File(path));
39 instances.put(path, ret);
42 } catch (Exception e) {
43 Log.error(FileBasedMailbox.class, e);
48 // Instance //////////////////////////////////////////////////////////////////////////////
51 private FileLock lock;
53 private int uidValidity;
55 // Helpers //////////////////////////////////////////////////////////////////////////////
57 private static void rmDashRf(File f) throws IOException {
58 if (!f.isDirectory()) { f.delete(); return; }
59 String[] children = f.list();
60 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
64 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
69 File lockfile = new File(this.path.getAbsolutePath() + slash + ".lock");
70 lock = new RandomAccessFile(lockfile, "rw").getChannel().tryLock();
73 Log.warn(this, "warning: blocking waiting for a lock on " + path);
74 lock = new RandomAccessFile(lockfile, "rw").getChannel().lock();
75 if (lock == null) throw new IOException("unable to lock FileBasedMailbox: " + path);
77 lockfile.deleteOnExit();
80 uidValidity = (int)(lockfile.lastModified() & 0xffffffff);
82 String[] files = path.list();
83 for(int i=0; i<files.length; i++) {
85 if (files[i].indexOf('.') <= 0) continue;
86 files[i] = files[i].substring(0, files[i].indexOf('.'));
87 int n = Integer.parseInt(files[i]);
88 if (n>=uidNext) uidNext = n;
89 } catch(Exception e) { Log.error(this, e); }
93 public String[] sort(String[] s) {
98 public String[] files() {
99 String[] s = path.list(filter);
100 Arrays.sort(s, comparator);
104 private static Comparator<String> comparator = new Comparator<String>() {
105 public int compare(String a, String b) {
106 if (a.indexOf('.')==-1) return a.compareTo(b);
107 if (b.indexOf('.')==-1) return a.compareTo(a);
108 int ai = Integer.parseInt(a.substring(0, a.indexOf('.')));
109 int bi = Integer.parseInt(b.substring(0, b.indexOf('.')));
110 return ai<bi ? -1 : ai>bi ? 1 : 0;
114 public Mailbox.Iterator iterator() { return new Iterator(); }
115 public String[] children() {
117 String[] list = sort(path.list());
118 for(int i=0; i<list.length; i++) {
119 File f = new File(path.getAbsolutePath() + slash + list[i]);
120 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
122 return (String[])vec.copyInto(new String[vec.size()]);
125 public int uidValidity() { return uidValidity; }
127 // UGLY: Apple Mail doesn't like UID=0, so we add one
128 public int uidNext() { return uidNext+1; }
130 public synchronized void insert(Message message, int flags) {
132 String name, fullname; File target, f;
133 for(int i = uidNext; ; i++) {
135 fullname = path.getAbsolutePath() + slash + name;
136 target = new File(fullname);
137 f = new File(target.getCanonicalPath() + "-");
138 if (!f.exists() && !target.exists()) break;
139 Log.error(this, "aieeee!!!! target of insert() already exists: " + target.getAbsolutePath());
141 Stream stream = new Stream(new FileOutputStream(f));
142 message.getStream().transcribe(stream);
144 f.renameTo(new File(fullname));
146 f = new File(fullname);
147 if ((flags & Mailbox.Flag.SEEN) == 0) f.setLastModified(MAGIC_DATE);
148 else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
149 } catch (IOException e) { throw new MailException.IOException(e); }
150 Log.info(this, path + " <= " + message.summary());
155 private static FilenameFilter filter =
156 new FilenameFilter() { public boolean accept(File dir, String name) {
157 return name.endsWith(".");
160 private class Iterator extends Mailbox.Default.Iterator {
162 String[] files = files();
163 private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
164 public boolean done() { return cur >= files.length; }
165 public boolean next() { cur++; return !done(); }
166 public boolean recent() { return false; }
167 public int nntpNumber() { return cur+1; } // FIXME: lame
168 public int imapNumber() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
170 // UGLY: Apple Mail doesn't like UID=0, so we add one
171 public int uid() { return done() ? -1 : 1+Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
173 public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
174 public int getFlags() {
175 return file().lastModified()==MAGIC_DATE ? 0 : Flag.SEEN;
177 public void setFlags(int flags) {
179 if ((flags & Mailbox.Flag.SEEN) == 0) f.setLastModified(MAGIC_DATE);
180 else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
183 public Headers head() {
184 if (done()) return null;
185 FileInputStream fis = null;
187 return new Headers.Original(new Stream(new FileInputStream(file())));
188 } catch (IOException e) { throw new MailException.IOException(e);
189 } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
191 public Message cur() {
192 FileInputStream fis = null;
194 return Message.newMessage(new Fountain.File(file()));
195 //} catch (IOException e) { throw new MailException.IOException(e);
196 } catch (Message.Malformed e) { throw new MailException(e.getMessage());
197 } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
201 public static class Servlet extends HttpServlet {
202 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
203 private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
204 String basename = request.getRequestURI();
205 PrintWriter pw = new PrintWriter(response.getWriter());
206 pw.println("<html>");
208 pw.println(" <frameset rows='30%,*'>");
209 //pw.println(" <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
210 //pw.println(" <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
211 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
212 pw.println(" <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
214 pw.println(" <frameset cols='150,*'>");
215 pw.println(" <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
216 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
218 pw.println(" </frameset>");
219 pw.println("</html>");
223 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
224 String frame = request.getParameter("frame");
225 String basename = request.getRequestURI();
227 if (frame == null) { frames(request, response, true); return; }
228 if (frame.equals("top")) { frames(request, response, false); return; }
229 if (frame.equals("banner")) { banner(request, response); return; }
230 if (frame.equals("topleft")) { return; }
232 if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
233 ServletContext cx = getServletContext();
234 String path = cx.getRealPath(request.getServletPath());
235 Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false);
236 if (mbox == null) throw new IOException("no such mailbox: " + path);
238 Vec msgs = new Vec();
239 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
240 String[] s = new String[4];
241 Message m = it.cur();
242 s[0] = (m.from==null?"":m.from.toString(true));
244 s[2] = (m.date + "").trim().replaceAll(" "," ");
245 s[3] = it.imapNumber() + "";
249 msgs.copyInto(messages = new String[msgs.size()][]);
251 if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
252 if ("topright".equals(frame)) { topright(request, response, messages); return; }
255 private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
257 PrintWriter pw = new PrintWriter(response.getWriter());
258 pw.println("<html>");
259 pw.println(" <head>");
260 pw.println(" <style>");
261 pw.println(" body { margin: 10px; }");
262 pw.println(" pre {");
263 pw.println(" font-family: monospace;");
264 pw.println(" background-color: #F0F0E0;");
265 pw.println(" color: rgb(0, 0, 0);");
266 pw.println(" padding: 5px;");
267 pw.println(" margin: 0px;");
268 pw.println(" overflow: auto;");
269 //pw.println(" width: 80%;");
270 //pw.println(" border-style: solid;");
271 //pw.println(" border-width: 1px;");
273 pw.println(" </style>");
274 pw.println(" </head>");
275 pw.println(" <body>");
276 if (request.getParameter("msgnum") != null) {
277 int target = Integer.parseInt(request.getParameter("msgnum"));
278 Mailbox.Iterator it = mbox.iterator();
280 if (it.imapNumber() == target)
282 if (it.cur() != null) {
283 pw.println(" <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
284 pw.println(" <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
285 Headers h = it.cur().headers;
286 pw.println(" Subject: " + it.cur().subject +"<br>");
287 pw.println(" From: " + it.cur().from +"<br>");
288 pw.println(" Date: " + it.cur().date +"<br>");
290 for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
291 String key = (String)e.nextElement();
292 if (key==null || key.length()==0 || key.equals("from") ||
293 key.equals("to") || key.equals("subject") || key.equals("date")) continue;
294 key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
295 String val = h.get(key);
296 for(int i=key.length(); i<15; i++)pw.print(" ");
301 pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
302 StringBuffer tgt = new StringBuffer();
303 it.cur().getBody().getStream().transcribe(tgt);
304 pw.println(tgt.toString());
305 pw.println(" </pre></td></tr></table>");
308 pw.println(" </body>");
309 pw.println("</html>");
314 private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
315 String basename = request.getServletPath();
316 String realpath = getServletContext().getRealPath(basename);
318 MailingList list = MailingList.getMailingList(realpath);
319 list.banner(request, response);
321 banner(request, response);
324 private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
325 PrintWriter pw = new PrintWriter(response.getWriter());
326 String basename = request.getRequestURI();
327 pw.println("<html>");
328 pw.println(" <head>");
329 pw.println(" <style>");
330 pw.println(" TH, TD, P, LI {");
331 pw.println(" font-family: helvetica, verdana, arial, sans-serif;");
332 pw.println(" font-size: 12px; ");
333 pw.println(" text-decoration:none; ");
335 pw.println(" body { margin: 10px; }");
336 pw.println(" a:link { color: #000; text-decoration: none; }");
337 pw.println(" a:active { color: #f00; text-decoration: none; }");
338 pw.println(" a:visited { color: #777; text-decoration: none; }");
339 pw.println(" a:hover { color: #000; text-decoration: none; }");
340 pw.println(" /* a:hover { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
341 pw.println(" </style>");
342 pw.println(" </head>");
343 pw.println(" <body onKeyPress='doKey(event.keyCode)'>");
344 pw.println(" <script>");
345 pw.println(" var chosen = null;");
346 pw.println(" var all = [];");
347 pw.println(" function doKey(x) {");
348 pw.println(" if (chosen == null) { choose(all[0]); return; }");
349 pw.println(" switch(x) {");
350 pw.println(" case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
351 pw.println(" case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
354 pw.println(" function choose(who) {");
355 pw.println(" who.style.background = '#ffc';");
356 pw.println(" if (chosen != null) chosen.style.background = '#ccc';");
357 pw.println(" parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
358 pw.println(" chosen = who;");
360 pw.println(" </script>");
361 pw.println(" <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
362 pw.println(" <tr><td style='padding: 4px' bgcolor=#eff7ff>");
364 banner(request, response);
365 pw.println(" </td></tr>");
366 pw.println(" <tr><td>");
367 pw.println(" <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
369 for(int i=0; i<messages.length; i++) {
371 String[] m = messages[i];
372 pw.println(" <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
373 "onmouseover='this.style.color=\"blue\"' "+
374 "onmouseout='this.style.color=\"black\"' "+
375 "onclick='choose(this);'>");
376 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
377 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
378 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
380 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
382 pw.println(" </table>");
383 pw.println(" </td></tr>");
384 pw.println(" </table></div>");
385 pw.println(" </body>");
386 pw.println("</html>");