be more tolerant of crud lying around in FilebasedMailboxes
[org.ibex.mail.git] / src / org / ibex / mail / FileBasedMailbox.java
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.
4
5 package org.ibex.mail;
6 import org.prevayler.*;
7 import org.ibex.mail.*;
8 import org.ibex.util.*;
9 import org.ibex.js.*;
10 import org.ibex.io.*;
11 import org.ibex.io.Fountain;
12 import java.io.*;
13 import java.nio.*;
14 import java.nio.channels.*;
15 import java.net.*;
16 import java.util.*;
17 import java.text.*;
18 import javax.servlet.*;
19 import javax.servlet.http.*;
20
21 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
22 public class FileBasedMailbox extends Mailbox.Default implements MailTree {
23
24     public static final long MAGIC_DATE =  0;
25     private static final char slash = File.separatorChar;
26
27     // FIXME: ideally this should be weak, but we end up getting duplicates of SqliteMailboxes
28     private static final HashMap<String,MailTree> instances = new HashMap<String,MailTree>();
29
30     public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
31
32     public MailTree slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
33
34     public void         rmdir(String subdir) { throw new RuntimeException("FIXME not implemented"); }
35     public void         rename(String subdir, MailTree newParent, String newName) { throw new RuntimeException("FIXME not implemented"); }
36     public Mailbox      getMailbox() { return this; }
37
38     public JS get(JS key) throws JSExn {
39         return (JS)slash(JSU.toString(key), true);
40     }
41
42     // FIXME: should be a File()
43     public static synchronized MailTree getFileBasedMailbox(String path, boolean create) {
44         if (path.endsWith(".sqlite")) path = path.substring(0, path.length()-".sqlite".length());
45         try {
46             MailTree ret = instances.get(path);
47             if (ret == null) {
48                 Log.error("n", "no match for " + path + " in " + instances.hashCode());
49                 if (new File(path+".sqlite").exists())
50                     ret = new SqliteMailbox(path+".sqlite");
51                 else {
52                     if (!create && !(new File(path).exists())) return null;
53                     ret = new FileBasedMailbox(new File(path));
54                 }
55                 instances.put(path, (MailTree)ret);
56                 Log.error("n", "filling " + path + " with " + instances.get(path));
57             }
58             return ret;
59         } catch (Exception e) {
60             Log.error(FileBasedMailbox.class, e);
61             return null;
62         }
63     }
64
65     // Instance //////////////////////////////////////////////////////////////////////////////
66
67     private File path;
68     private FileLock lock;
69     private int uidNext;
70     private int uidValidity;
71
72     // Helpers //////////////////////////////////////////////////////////////////////////////
73
74     private static void rmDashRf(File f) throws IOException {
75         if (!f.isDirectory()) { f.delete(); return; }
76         String[] children = f.list();
77         for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
78         f.delete();
79     }
80
81     private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
82         this.path = path;
83         path.mkdirs();
84
85         // acquire lock
86         File lockfile = new File(this.path.getAbsolutePath() + slash + ".lock");
87         lock = new RandomAccessFile(lockfile, "rw").getChannel().tryLock();
88         // FIXME!!!
89         /*
90         if (lock == null) {
91             Log.warn(this, "warning: blocking waiting for a lock on " + path);
92             lock = new RandomAccessFile(lockfile, "rw").getChannel().lock();
93             if (lock == null) throw new IOException("unable to lock FileBasedMailbox: " + path);
94         }
95         lockfile.deleteOnExit();
96         */
97
98         uidValidity = (int)(lockfile.lastModified() & 0xffffffff);
99         uidNext = 0;
100         String[] files = path.list();
101         for(int i=0; i<files.length; i++) {
102             try {
103                 if (files[i].indexOf('.') <= 0) continue;
104                 files[i] = files[i].substring(0, files[i].indexOf('.'));
105                 try {
106                     int n = Integer.parseInt(files[i]);
107                     if (n>=uidNext) uidNext = n;
108                 } catch (NumberFormatException nfe) { continue; }
109             } catch(Exception e) { Log.error(this, e); }
110         }
111     }
112
113     public String[] sort(String[] s) {
114         Arrays.sort(s);
115         return s;
116     }
117
118     public String[] files() {
119         String[] s = path.list(filter);
120         Arrays.sort(s, comparator);
121         return s;
122     }
123     
124     private static Comparator<String> comparator = new Comparator<String>() {
125         public int compare(String a, String b) {
126             if (a.indexOf('.')==-1) return a.compareTo(b);
127             if (b.indexOf('.')==-1) return a.compareTo(a);
128             int ai = Integer.parseInt(a.substring(0, a.indexOf('.')));
129             int bi = Integer.parseInt(b.substring(0, b.indexOf('.')));
130             return ai<bi ? -1 : ai>bi ? 1 : 0;
131         }
132     };
133
134     public Mailbox.Iterator  iterator()           { return new Iterator(); }
135     public String[] children() {
136         Vec vec = new Vec();
137         String[] list = sort(path.list());
138         for(int i=0; i<list.length; i++) {
139             File f = new File(path.getAbsolutePath() + slash + list[i]);
140             if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
141             if (!f.isDirectory() && f.getName().endsWith(".sqlite"))
142                 vec.addElement(list[i].substring(0, list[i].length()-".sqlite".length()));
143         }
144         return (String[])vec.copyInto(new String[vec.size()]);
145     }
146
147     public int uidValidity() { return uidValidity; }
148
149     // UGLY: Apple Mail doesn't like UID=0, so we add one
150     public int uidNext() {  return uidNext+1; }
151
152     public synchronized void insert(Message message, int flags) {
153         try {
154             String name, fullname; File target, f;
155             for(int i = uidNext; ; i++) {
156                 name = i + ".";
157                 fullname = path.getAbsolutePath() + slash + name;
158                 target = new File(fullname);
159                 f = new File(target.getCanonicalPath() + "-");
160                 if (!f.exists() && !target.exists()) break;
161                 Log.error(this, "aieeee!!!! target of insert() already exists: " + target.getAbsolutePath());
162             }
163             Stream stream = new Stream(new FileOutputStream(f));
164             message.getStream().transcribe(stream);
165             stream.close();
166             f.renameTo(new File(fullname));
167             uidNext++;
168             f = new File(fullname);
169             if ((flags & Mailbox.Flag.SEEN) == 0)  f.setLastModified(MAGIC_DATE);
170             else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
171         } catch (IOException e) { throw new MailException.IOException(e); }
172         Log.info(this, path + " <= " + message.summary());
173     }
174
175     
176
177     private static FilenameFilter filter =
178         new FilenameFilter() { public boolean accept(File dir, String name) {
179             return name.endsWith(".");
180         } };
181
182     private class Iterator extends Mailbox.Default.Iterator {
183         int cur = -1;
184         String[] files = files();
185         private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
186         public boolean done() { return cur >= files.length; }
187         public boolean next() { cur++; return !done(); }
188         public boolean recent() { return false; }
189         public int nntpNumber() { return cur+1; }  // FIXME: lame
190         public int imapNumber() { return cur+1; }  // EUDORA insists that message numbers start at 1, not 0
191
192         // UGLY: Apple Mail doesn't like UID=0, so we add one
193         public int uid() { return done() ? -1 : 1+Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
194         public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
195         public int  getFlags() { return file().lastModified()==MAGIC_DATE ? 0 : Flag.SEEN; }
196         public void setFlags(int flags) {
197             File f = file();
198             if ((flags & Mailbox.Flag.SEEN) == 0)  f.setLastModified(MAGIC_DATE);
199             else if (f.lastModified()==MAGIC_DATE) f.setLastModified(System.currentTimeMillis());
200             // FIXME: other flags?
201         }
202         public Headers head() { return done() ? null : new Headers(new Fountain.File(file())); }
203         public Message cur() { return Message.newMessage(new Fountain.File(file())); }
204     }
205
206     // there's no reason this has to operate on a FileBasedMailbox -- it could operate on arbitrary mailboxes!
207     // use this for file attachments: http://jakarta.apache.org/commons/fileupload/
208     public static class Servlet extends HttpServlet {
209         public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
210         private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
211             String basename = request.getRequestURI();
212             PrintWriter pw = new PrintWriter(response.getWriter());
213             pw.println("<html>");
214             if (top) {
215                 pw.println("  <frameset rows='30%,*'>");
216                 //pw.println("    <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
217                 //pw.println("    <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
218                 pw.println("    <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
219                 pw.println("    <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
220             } else {
221                 pw.println("  <frameset cols='150,*'>");
222                 pw.println("    <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
223                 pw.println("    <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
224             }
225             pw.println("  </frameset>");
226             pw.println("</html>");
227             pw.flush();
228         }
229
230         public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
231             String frame = request.getParameter("frame");
232             String basename = request.getRequestURI();
233
234             if (frame == null) { frames(request, response, true); return; }
235             if (frame.equals("top")) { frames(request, response, false); return; }
236             if (frame.equals("banner")) { banner(request, response); return; }
237             if (frame.equals("topleft")) { return; }
238
239             if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
240             ServletContext cx = getServletContext();
241             String path = cx.getRealPath(request.getServletPath());
242             Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false).getMailbox();
243             if (mbox == null) throw new IOException("no such mailbox: " + path);
244
245             Vec msgs = new Vec();
246             for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
247                 String[] s = new String[4];
248                 Message m = it.cur();
249                 s[0] = (m.from==null?"":m.from.toString(true));
250                 s[1] = m.subject;
251                 s[2] = (m.date + "").trim().replaceAll(" ","&nbsp;");
252                 s[3] = it.imapNumber() + "";
253                 msgs.addElement(s);
254             }
255             String[][] messages;
256             msgs.copyInto(messages = new String[msgs.size()][]);
257
258             if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
259             if ("topright".equals(frame)) { topright(request, response, messages); return; }
260         }
261
262         private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
263             throws IOException {
264             PrintWriter pw = new PrintWriter(response.getWriter());
265             pw.println("<html>");
266             pw.println("  <head>");
267             pw.println("  <style>");
268             pw.println("      body { margin: 10px; }");
269             pw.println("      pre {");
270             pw.println("         font-family: monospace;");
271             pw.println("         background-color:  #F0F0E0;");
272             pw.println("         color: rgb(0, 0, 0);");
273             pw.println("         padding: 5px;");
274             pw.println("         margin: 0px;");
275             pw.println("         overflow: auto;");
276             //pw.println("         width: 80%;");
277             //pw.println("         border-style: solid;");
278             //pw.println("         border-width: 1px;");
279             pw.println("      }");
280             pw.println("  </style>");
281             pw.println("  </head>");
282             pw.println("  <body>");
283             if (request.getParameter("msgnum") != null) {
284                 int target = Integer.parseInt(request.getParameter("msgnum"));
285                 Mailbox.Iterator it = mbox.iterator();
286                 while(it.next())
287                     if (it.imapNumber() == target)
288                         break;
289                 if (it.cur() != null) {
290                     pw.println("    <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
291                     pw.println("      <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
292                     Headers h = it.cur().headers;
293                     pw.println(" Subject: " + it.cur().subject +"<br>");
294                     pw.println("    From: " + it.cur().from +"<br>");
295                     pw.println("    Date: " + it.cur().date +"<br>");
296                         /*
297                     for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
298                         String key = (String)e.nextElement();
299                         if (key==null || key.length()==0 || key.equals("from") ||
300                             key.equals("to") || key.equals("subject") || key.equals("date")) continue;
301                         key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
302                         String val = h.get(key);
303                         for(int i=key.length(); i<15; i++)pw.print(" ");
304                         pw.print(key+": ");
305                         pw.println(val);
306                     }
307                         */
308                     pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
309                     StringBuffer tgt = new StringBuffer();
310                     it.cur().getBody().getStream().transcribe(tgt);
311                     pw.println(tgt.toString());
312                     pw.println("    </pre></td></tr></table>");
313                 }
314             }
315             pw.println("  </body>");
316             pw.println("</html>");
317             pw.flush();
318             pw.close();
319         }
320         
321         private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
322             String basename = request.getServletPath();
323             String realpath = getServletContext().getRealPath(basename);
324             /*
325             MailingList list = MailingList.getMailingList(realpath);
326             list.banner(request, response);
327             */
328             banner(request, response);
329         }
330
331         private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
332             PrintWriter pw = new PrintWriter(response.getWriter());
333             String basename = request.getRequestURI();
334             pw.println("<html>");
335             pw.println("  <head>");
336             pw.println("    <style>");
337             pw.println("      TH, TD, P, LI {");
338             pw.println("          font-family: helvetica, verdana, arial, sans-serif;");
339             pw.println("          font-size: 12px;  ");
340             pw.println("          text-decoration:none; ");
341             pw.println("      }");
342             pw.println("      body { margin: 10px; }");
343             pw.println("      a:link    { color: #000; text-decoration: none; }");
344             pw.println("      a:active  { color: #f00; text-decoration: none; }");
345             pw.println("      a:visited { color: #777; text-decoration: none; }");
346             pw.println("      a:hover   { color: #000; text-decoration: none; }");
347             pw.println("      /* a:hover   { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
348             pw.println("    </style>");
349             pw.println("  </head>");
350             pw.println("  <body onKeyPress='doKey(event.keyCode)'>");
351             pw.println("    <script>");
352             pw.println("      var chosen = null;");
353             pw.println("      var all = [];");
354             pw.println("      function doKey(x) {");
355             pw.println("          if (chosen == null) { choose(all[0]); return; }");
356             pw.println("          switch(x) {");
357             pw.println("              case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
358             pw.println("              case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
359             pw.println("          }");
360             pw.println("      }");
361             pw.println("      function choose(who) {");
362             pw.println("          who.style.background = '#ffc';");
363             pw.println("          if (chosen != null) chosen.style.background = '#ccc';");
364             pw.println("          parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
365             pw.println("          chosen = who;");
366             pw.println("      }");
367             pw.println("    </script>");
368             pw.println("    <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
369             pw.println("    <tr><td style='padding: 4px' bgcolor=#eff7ff>");
370             pw.flush();
371             banner(request, response);
372             pw.println("    </td></tr>");
373             pw.println("    <tr><td>");
374             pw.println("    <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
375             boolean odd=true;
376             for(int i=0; i<messages.length; i++) {
377                 odd = !odd;
378                 String[] m = messages[i];
379                 pw.println("      <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
380                            "onmouseover='this.style.color=\"blue\"' "+
381                            "onmouseout='this.style.color=\"black\"' "+
382                            "onclick='choose(this);'>");
383                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
384                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
385                 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
386                 pw.println("</tr>");
387                 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
388             }
389             pw.println("    </table>");
390             pw.println("    </td></tr>");
391             pw.println("    </table></div>");
392             pw.println("  </body>");
393             pw.println("</html>");
394             pw.flush();
395             pw.close();
396         }
397     }
398 }