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.
5 package org.ibex.mail.target;
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,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
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 FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
31 FileBasedMailbox ret = instances.get(path);
33 if (!create && !(new File(path).exists())) return null;
34 instances.put(path, ret = new FileBasedMailbox(new File(path)));
37 } catch (Exception e) {
38 Log.error(FileBasedMailbox.class, e);
43 // Instance //////////////////////////////////////////////////////////////////////////////
46 private FileLock lock;
48 private int uidValidity;
50 // Helpers //////////////////////////////////////////////////////////////////////////////
52 private static void rmDashRf(File f) throws IOException {
53 if (!f.isDirectory()) { f.delete(); return; }
54 String[] children = f.list();
55 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
59 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
64 File lockfile = new File(this.path.getAbsolutePath() + slash + ".lock");
65 lock = new RandomAccessFile(lockfile, "rw").getChannel().tryLock();
66 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
67 uidValidity = (int)(lockfile.lastModified() & 0xffffffff);
69 String[] files = path.list();
70 for(int i=0; i<files.length; i++) {
72 if (files[i].indexOf('.') != -1) files[i] = files[i].substring(0, files[i].indexOf('.'));
73 int n = Integer.parseInt(files[i]);
74 if (n>=uidNext) uidNext = n;
75 } catch(Exception e) { /* DELIBERATE */ }
80 public Mailbox.Iterator iterator() { return new Iterator(); }
81 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
82 public String[] children() {
84 String[] list = path.list();
85 for(int i=0; i<list.length; i++) {
86 File f = new File(path.getAbsolutePath() + slash + list[i]);
87 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
89 return (String[])vec.copyInto(new String[vec.size()]);
92 public int uidValidity() { return uidValidity; }
93 public int uidNext() { return uidNext; }
94 public synchronized void add(Message message, int flags) {
96 String name, fullname; File target, f;
97 for(int i = uidNext; ; i++) {
99 fullname = path.getAbsolutePath() + slash + name;
100 target = new File(fullname);
101 f = new File(target.getCanonicalPath() + "-");
102 if (!f.exists() && !target.exists()) break;
103 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
105 Stream stream = new Stream(new FileOutputStream(f));
106 message.getStream().transcribe(stream);
108 f.renameTo(new File(fullname));
110 f = new File(fullname);
111 if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
112 } catch (IOException e) { throw new MailException.IOException(e); }
113 Log.info(this, path + " <= " + message.summary());
116 private class Iterator extends Mailbox.Default.Iterator {
118 String[] files = path.list(new FilenameFilter() { public boolean accept(File dir, String name) {
119 return name.endsWith(".");
121 private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
122 public boolean done() { return cur >= files.length; }
123 public boolean next() { cur++; return !done(); }
124 public boolean seen() { return false; }
125 public boolean recent() { return false; }
126 public int num() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
127 public int uid() { return done() ? -1 : Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
128 public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
129 public void seen(boolean seen) { }
130 public Headers head() {
131 if (done()) return null;
132 FileInputStream fis = null;
134 return new Headers.Original(new Stream(new FileInputStream(file())));
135 } catch (IOException e) { throw new MailException.IOException(e);
136 } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
138 public Message cur() {
139 FileInputStream fis = null;
141 return Message.newMessage(new Fountain.File(file()));
142 //} catch (IOException e) { throw new MailException.IOException(e);
143 } catch (Message.Malformed e) { throw new MailException(e.getMessage());
144 } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
148 public static class Servlet extends HttpServlet {
149 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
150 private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
151 String basename = request.getRequestURI();
152 PrintWriter pw = new PrintWriter(response.getWriter());
153 pw.println("<html>");
155 pw.println(" <frameset rows='30%,*'>");
156 //pw.println(" <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
157 //pw.println(" <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
158 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
159 pw.println(" <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
161 pw.println(" <frameset cols='150,*'>");
162 pw.println(" <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
163 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
165 pw.println(" </frameset>");
166 pw.println("</html>");
170 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
171 String frame = request.getParameter("frame");
172 String basename = request.getRequestURI();
174 if (frame == null) { frames(request, response, true); return; }
175 if (frame.equals("top")) { frames(request, response, false); return; }
176 if (frame.equals("banner")) { banner(request, response); return; }
177 if (frame.equals("topleft")) { return; }
179 if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
180 ServletContext cx = getServletContext();
181 String path = cx.getRealPath(request.getServletPath());
182 Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false);
183 if (mbox == null) throw new IOException("no such mailbox: " + path);
185 Vec msgs = new Vec();
186 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
187 String[] s = new String[4];
188 Message m = it.cur();
189 s[0] = (m.from==null?"":m.from.toString(true));
191 s[2] = (m.date + "").trim().replaceAll(" "," ");
192 s[3] = it.num() + "";
196 msgs.copyInto(messages = new String[msgs.size()][]);
198 if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
199 if ("topright".equals(frame)) { topright(request, response, messages); return; }
202 private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
204 PrintWriter pw = new PrintWriter(response.getWriter());
205 pw.println("<html>");
206 pw.println(" <head>");
207 pw.println(" <style>");
208 pw.println(" body { margin: 10px; }");
209 pw.println(" pre {");
210 pw.println(" font-family: monospace;");
211 pw.println(" background-color: #F0F0E0;");
212 pw.println(" color: rgb(0, 0, 0);");
213 pw.println(" padding: 5px;");
214 pw.println(" margin: 0px;");
215 pw.println(" overflow: auto;");
216 //pw.println(" width: 80%;");
217 //pw.println(" border-style: solid;");
218 //pw.println(" border-width: 1px;");
220 pw.println(" </style>");
221 pw.println(" </head>");
222 pw.println(" <body>");
223 if (request.getParameter("msgnum") != null) {
224 int target = Integer.parseInt(request.getParameter("msgnum"));
225 Mailbox.Iterator it = mbox.iterator();
227 if (it.num() == target)
229 if (it.cur() != null) {
230 pw.println(" <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
231 pw.println(" <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
232 Headers h = it.cur().headers;
233 pw.println(" Subject: " + it.cur().subject +"<br>");
234 pw.println(" From: " + it.cur().from +"<br>");
235 pw.println(" Date: " + it.cur().date +"<br>");
237 for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
238 String key = (String)e.nextElement();
239 if (key==null || key.length()==0 || key.equals("from") ||
240 key.equals("to") || key.equals("subject") || key.equals("date")) continue;
241 key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
242 String val = h.get(key);
243 for(int i=key.length(); i<15; i++)pw.print(" ");
248 pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
249 StringBuffer tgt = new StringBuffer();
250 it.cur().getBody().getStream().transcribe(tgt);
251 pw.println(tgt.toString());
252 pw.println(" </pre></td></tr></table>");
255 pw.println(" </body>");
256 pw.println("</html>");
261 private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
262 String basename = request.getServletPath();
263 String realpath = getServletContext().getRealPath(basename);
264 MailingList list = MailingList.getMailingList(realpath);
265 list.banner(request, response);
268 private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
269 PrintWriter pw = new PrintWriter(response.getWriter());
270 String basename = request.getRequestURI();
271 pw.println("<html>");
272 pw.println(" <head>");
273 pw.println(" <style>");
274 pw.println(" TH, TD, P, LI {");
275 pw.println(" font-family: helvetica, verdana, arial, sans-serif;");
276 pw.println(" font-size: 12px; ");
277 pw.println(" text-decoration:none; ");
279 pw.println(" body { margin: 10px; }");
280 pw.println(" a:link { color: #000; text-decoration: none; }");
281 pw.println(" a:active { color: #f00; text-decoration: none; }");
282 pw.println(" a:visited { color: #777; text-decoration: none; }");
283 pw.println(" a:hover { color: #000; text-decoration: none; }");
284 pw.println(" /* a:hover { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
285 pw.println(" </style>");
286 pw.println(" </head>");
287 pw.println(" <body onKeyPress='doKey(event.keyCode)'>");
288 pw.println(" <script>");
289 pw.println(" var chosen = null;");
290 pw.println(" var all = [];");
291 pw.println(" function doKey(x) {");
292 pw.println(" if (chosen == null) { choose(all[0]); return; }");
293 pw.println(" switch(x) {");
294 pw.println(" case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
295 pw.println(" case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
298 pw.println(" function choose(who) {");
299 pw.println(" who.style.background = '#ffc';");
300 pw.println(" if (chosen != null) chosen.style.background = '#ccc';");
301 pw.println(" parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
302 pw.println(" chosen = who;");
304 pw.println(" </script>");
305 pw.println(" <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
306 pw.println(" <tr><td style='padding: 4px' bgcolor=#eff7ff>");
308 banner(request, response);
309 pw.println(" </td></tr>");
310 pw.println(" <tr><td>");
311 pw.println(" <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
313 for(int i=0; i<messages.length; i++) {
315 String[] m = messages[i];
316 pw.println(" <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
317 "onmouseover='this.style.color=\"blue\"' "+
318 "onmouseout='this.style.color=\"black\"' "+
319 "onclick='choose(this);'>");
320 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
321 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
322 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
324 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
326 pw.println(" </table>");
327 pw.println(" </td></tr>");
328 pw.println(" </table></div>");
329 pw.println(" </body>");
330 pw.println("</html>");