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,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();
71 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
72 uidValidity = (int)(lockfile.lastModified() & 0xffffffff);
74 String[] files = path.list();
75 for(int i=0; i<files.length; i++) {
77 if (files[i].indexOf('.') == -1) continue;
78 if (files[i].charAt(0) == '.') continue;
79 files[i] = files[i].substring(0, files[i].indexOf('.'));
80 int n = Integer.parseInt(files[i]);
81 if (n>=uidNext) uidNext = n;
82 } catch(Exception e) { Log.error(this, e); }
86 public String[] sort(String[] s) {
91 public String[] files() {
92 String[] s = path.list(filter);
93 Arrays.sort(s, comparator);
97 private static Comparator<String> comparator = new Comparator<String>() {
98 public int compare(String a, String b) {
99 if (a.indexOf('.')==-1) return a.compareTo(b);
100 if (b.indexOf('.')==-1) return a.compareTo(a);
101 int ai = Integer.parseInt(a.substring(0, a.indexOf('.')));
102 int bi = Integer.parseInt(b.substring(0, b.indexOf('.')));
103 return ai<bi ? -1 : ai>bi ? 1 : 0;
107 public Mailbox.Iterator iterator() { return new Iterator(); }
108 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
109 public String[] children() {
111 String[] list = sort(path.list());
112 for(int i=0; i<list.length; i++) {
113 File f = new File(path.getAbsolutePath() + slash + list[i]);
114 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
116 return (String[])vec.copyInto(new String[vec.size()]);
119 public int uidValidity() { return uidValidity; }
120 public int uidNext() { return uidNext; }
121 public synchronized void add(Message message, int flags) {
123 String name, fullname; File target, f;
124 for(int i = uidNext; ; i++) {
126 fullname = path.getAbsolutePath() + slash + name;
127 target = new File(fullname);
128 f = new File(target.getCanonicalPath() + "-");
129 if (!f.exists() && !target.exists()) break;
130 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
132 Stream stream = new Stream(new FileOutputStream(f));
133 message.getStream().transcribe(stream);
135 f.renameTo(new File(fullname));
137 f = new File(fullname);
138 if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
139 } catch (IOException e) { throw new MailException.IOException(e); }
140 Log.info(this, path + " <= " + message.summary());
143 private static FilenameFilter filter =
144 new FilenameFilter() { public boolean accept(File dir, String name) {
145 return name.endsWith(".");
148 private class Iterator extends Mailbox.Default.Iterator {
150 String[] files = files();
151 private File file() { return new File(path.getAbsolutePath() + slash + files[cur]); }
152 public boolean done() { return cur >= files.length; }
153 public boolean next() { cur++; return !done(); }
154 public boolean seen() { return false; }
155 public boolean recent() { return false; }
156 public int num() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
157 public int uid() { return done() ? -1 : Integer.parseInt(files[cur].substring(0, files[cur].length()-1)); }
158 public void delete() { File f = file(); if (f != null && f.exists()) f.delete(); }
159 public void seen(boolean seen) { }
160 public Headers head() {
161 if (done()) return null;
162 FileInputStream fis = null;
164 return new Headers.Original(new Stream(new FileInputStream(file())));
165 } catch (IOException e) { throw new MailException.IOException(e);
166 } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
168 public Message cur() {
169 FileInputStream fis = null;
171 return Message.newMessage(new Fountain.File(file()));
172 //} catch (IOException e) { throw new MailException.IOException(e);
173 } catch (Message.Malformed e) { throw new MailException(e.getMessage());
174 } finally { if (fis != null) try { fis.close(); } catch (Exception e) { /* DELIBERATE */ } }
178 public static class Servlet extends HttpServlet {
179 public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); }
180 private void frames(HttpServletRequest request, HttpServletResponse response, boolean top) throws IOException {
181 String basename = request.getRequestURI();
182 PrintWriter pw = new PrintWriter(response.getWriter());
183 pw.println("<html>");
185 pw.println(" <frameset rows='30%,*'>");
186 //pw.println(" <frame src='"+basename+"?frame=banner' marginwidth=0 marginheight=0 name=banner/>");
187 //pw.println(" <frame src='"+basename+"?frame=top' marginwidth=0 marginheight=0 name=top/>");
188 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
189 pw.println(" <frame src='"+basename+"?frame=bottom' marginwidth=0 marginheight=0 name='bottom'/>");
191 pw.println(" <frameset cols='150,*'>");
192 pw.println(" <frame src='"+basename+"?frame=topleft' marginwidth=0 marginheight=0 name=topleft/>");
193 pw.println(" <frame src='"+basename+"?frame=topright' marginwidth=0 marginheight=0 name=topright/>");
195 pw.println(" </frameset>");
196 pw.println("</html>");
200 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
201 String frame = request.getParameter("frame");
202 String basename = request.getRequestURI();
204 if (frame == null) { frames(request, response, true); return; }
205 if (frame.equals("top")) { frames(request, response, false); return; }
206 if (frame.equals("banner")) { banner(request, response); return; }
207 if (frame.equals("topleft")) { return; }
209 if (request.getServletPath().indexOf("..") != -1) throw new IOException(".. not allowed in image paths");
210 ServletContext cx = getServletContext();
211 String path = cx.getRealPath(request.getServletPath());
212 Mailbox mbox = FileBasedMailbox.getFileBasedMailbox(path, false);
213 if (mbox == null) throw new IOException("no such mailbox: " + path);
215 Vec msgs = new Vec();
216 for(Mailbox.Iterator it = mbox.iterator(); it.next();) {
217 String[] s = new String[4];
218 Message m = it.cur();
219 s[0] = (m.from==null?"":m.from.toString(true));
221 s[2] = (m.date + "").trim().replaceAll(" "," ");
222 s[3] = it.num() + "";
226 msgs.copyInto(messages = new String[msgs.size()][]);
228 if ("bottom".equals(frame)) { bottom(request, response, messages, mbox); return; }
229 if ("topright".equals(frame)) { topright(request, response, messages); return; }
232 private void bottom(HttpServletRequest request, HttpServletResponse response, String[][] messages, Mailbox mbox)
234 PrintWriter pw = new PrintWriter(response.getWriter());
235 pw.println("<html>");
236 pw.println(" <head>");
237 pw.println(" <style>");
238 pw.println(" body { margin: 10px; }");
239 pw.println(" pre {");
240 pw.println(" font-family: monospace;");
241 pw.println(" background-color: #F0F0E0;");
242 pw.println(" color: rgb(0, 0, 0);");
243 pw.println(" padding: 5px;");
244 pw.println(" margin: 0px;");
245 pw.println(" overflow: auto;");
246 //pw.println(" width: 80%;");
247 //pw.println(" border-style: solid;");
248 //pw.println(" border-width: 1px;");
250 pw.println(" </style>");
251 pw.println(" </head>");
252 pw.println(" <body>");
253 if (request.getParameter("msgnum") != null) {
254 int target = Integer.parseInt(request.getParameter("msgnum"));
255 Mailbox.Iterator it = mbox.iterator();
257 if (it.num() == target)
259 if (it.cur() != null) {
260 pw.println(" <table width=100% border=0 cellspacing=0 style='border: 1px black solid; background-color:#F0F0E0;'>");
261 pw.println(" <tr style='border: 1px black solid; font-family: monospace'><td style='padding: 5px'>");
262 Headers h = it.cur().headers;
263 pw.println(" Subject: " + it.cur().subject +"<br>");
264 pw.println(" From: " + it.cur().from +"<br>");
265 pw.println(" Date: " + it.cur().date +"<br>");
267 for(java.util.Enumeration e = h.names(); e.hasMoreElements();) {
268 String key = (String)e.nextElement();
269 if (key==null || key.length()==0 || key.equals("from") ||
270 key.equals("to") || key.equals("subject") || key.equals("date")) continue;
271 key = Character.toUpperCase(key.charAt(0)) + key.substring(1);
272 String val = h.get(key);
273 for(int i=key.length(); i<15; i++)pw.print(" ");
278 pw.print("</td></tr><tr><td style='border-top: 1px black; border-top-style: dotted;'><pre>");
279 StringBuffer tgt = new StringBuffer();
280 it.cur().getBody().getStream().transcribe(tgt);
281 pw.println(tgt.toString());
282 pw.println(" </pre></td></tr></table>");
285 pw.println(" </body>");
286 pw.println("</html>");
291 private void banner(HttpServletRequest request, HttpServletResponse response) throws IOException {
292 String basename = request.getServletPath();
293 String realpath = getServletContext().getRealPath(basename);
295 MailingList list = MailingList.getMailingList(realpath);
296 list.banner(request, response);
298 banner(request, response);
301 private void topright(HttpServletRequest request, HttpServletResponse response, String[][] messages) throws IOException {
302 PrintWriter pw = new PrintWriter(response.getWriter());
303 String basename = request.getRequestURI();
304 pw.println("<html>");
305 pw.println(" <head>");
306 pw.println(" <style>");
307 pw.println(" TH, TD, P, LI {");
308 pw.println(" font-family: helvetica, verdana, arial, sans-serif;");
309 pw.println(" font-size: 12px; ");
310 pw.println(" text-decoration:none; ");
312 pw.println(" body { margin: 10px; }");
313 pw.println(" a:link { color: #000; text-decoration: none; }");
314 pw.println(" a:active { color: #f00; text-decoration: none; }");
315 pw.println(" a:visited { color: #777; text-decoration: none; }");
316 pw.println(" a:hover { color: #000; text-decoration: none; }");
317 pw.println(" /* a:hover { color: #00f; text-decoration: none; border-bottom: 1px dotted; } */");
318 pw.println(" </style>");
319 pw.println(" </head>");
320 pw.println(" <body onKeyPress='doKey(event.keyCode)'>");
321 pw.println(" <script>");
322 pw.println(" var chosen = null;");
323 pw.println(" var all = [];");
324 pw.println(" function doKey(x) {");
325 pw.println(" if (chosen == null) { choose(all[0]); return; }");
326 pw.println(" switch(x) {");
327 pw.println(" case 112: if (chosen.id > 0) choose(all[chosen.id-1]); break;");
328 pw.println(" case 110: if (chosen.id < (all.length-1)) choose(all[1+(1*chosen.id)]); break;");
331 pw.println(" function choose(who) {");
332 pw.println(" who.style.background = '#ffc';");
333 pw.println(" if (chosen != null) chosen.style.background = '#ccc';");
334 pw.println(" parent.parent.bottom.location='"+basename+"?frame=bottom&msgnum='+who.id;");
335 pw.println(" chosen = who;");
337 pw.println(" </script>");
338 pw.println(" <div style='border: 1px black solid;'><table width=100% border=0 cellpadding=0 cellspacing=0>");
339 pw.println(" <tr><td style='padding: 4px' bgcolor=#eff7ff>");
341 banner(request, response);
342 pw.println(" </td></tr>");
343 pw.println(" <tr><td>");
344 pw.println(" <table width=100% cellpadding=0 cellspacing=0 style='border-top: 1px black solid; cursor:pointer;'>");
346 for(int i=0; i<messages.length; i++) {
348 String[] m = messages[i];
349 pw.println(" <tr style='cursor:pointer; background: "+(odd?"#e8eef7":"white")+"' id='"+m[3]+"' "+
350 "onmouseover='this.style.color=\"blue\"' "+
351 "onmouseout='this.style.color=\"black\"' "+
352 "onclick='choose(this);'>");
353 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[0]+"</td>");
354 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[1]+"</td>");
355 pw.println("<td style='cursor:pointer; padding:5px; padding-bottom:2px'>"+m[2]+"</td>");
357 pw.println("<script> all["+i+"] = document.getElementById('"+i+"'); </script>");
359 pw.println(" </table>");
360 pw.println(" </td></tr>");
361 pw.println(" </table></div>");
362 pw.println(" </body>");
363 pw.println("</html>");