1 package org.ibex.mail.target;
2 import org.prevayler.*;
3 import org.ibex.mail.*;
4 import org.ibex.util.*;
8 import java.nio.channels.*;
13 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
14 public class FileBasedMailbox extends Mailbox.Default {
16 public static final long MAGIC_DATE = 0;
18 public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
19 private static final char slash = File.separatorChar;
20 private static final WeakHashMap<String,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
21 public Mailbox slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
23 // FIXME: should be a File()
24 public static synchronized FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
26 FileBasedMailbox ret = instances.get(path);
28 if (!create && !(new File(path).exists())) return null;
29 instances.put(path, ret = new FileBasedMailbox(new File(path)));
32 } catch (Exception e) {
33 Log.error(FileBasedMailbox.class, e);
39 // Instance //////////////////////////////////////////////////////////////////////////////
42 private FileLock lock;
43 private Prevayler prevayler;
46 public static class Cache implements Serializable {
47 public final int uidValidity = new Random().nextInt();
48 private final Hashtable<String,Entry> byname = new Hashtable<String,Entry>();
49 private final Hashtable<Integer,Entry> byuid = new Hashtable<Integer,Entry>();
50 private final ArrayList<Entry> linear = new ArrayList<Entry>();
51 public final File dir;
52 private int uidNext = 0;
54 public Cache(File dir) { this.dir = dir; }
56 public void init(final Prevayler prevayler) throws IOException {
58 Log.info(this, "initializing maildir " + dir.getParent());
59 boolean invalid = false;
60 ArrayList<Transaction> kill = new ArrayList<Transaction>();
61 for(String s : byname.keySet()) {
62 String name = dir.getParent() + slash + s;
63 if (!new File(name).exists() && !new File(name+"s").exists()) {
64 Log.error(this, "dropping message " + name);
65 kill.add(new Drop(byname.get(s).uid()));
68 for(Transaction t : kill) prevayler.execute(t);
69 for(String file : new File(dir.getParent()).list())
70 if (file.charAt(0)!='.' && !(new File(dir.getParent() + slash + file).isDirectory())) {
71 if (get(file) == null) new Entry(this, prevayler, file);
72 else if ((new File(dir.getParent() + slash + file).lastModified() == MAGIC_DATE) != get(file).seen())
73 prevayler.execute(new Seen(get(file).uid(), !get(file).seen()));
75 Log.info(this, " done initializing maildir " + dir.getParent());
76 new Thread() { public void run() {
77 try { prevayler.takeSnapshot(); } catch (Exception e) { Log.error(this, e); }
81 public static class Drop implements Transaction {
83 public Drop(int uid) { this.uid = uid; }
84 public void executeOn(Object o, Date now) {
87 c.byname.remove(e.name);
93 public synchronized int size() { return linear.size(); }
94 public synchronized int uidNext(boolean increment) { return increment ? uidNext++ : uidNext; }
95 public synchronized Entry get(int uid) { return byuid.get(uid); }
96 public synchronized Entry getLinear(int num) { return linear.get(num); }
97 public synchronized Entry get(String name) {
98 if (name.endsWith("s")) name = name.substring(0, name.length() - 1);
99 return byname.get(name);
102 public static class Entry implements Serializable {
103 private final byte[] header;
104 public final String name;
106 private boolean seen;
108 public MIME.Headers headers() { return new MIME.Headers(new Stream(new ByteArrayInputStream(header)), true); }
109 public Entry(Cache cache, Prevayler prevayler, String name) throws IOException {
110 File f = new File(cache.dir.getParent()+slash+name);
111 seen = f.lastModified() == MAGIC_DATE;
113 header = new MIME.Headers(new Stream(new FileInputStream(f)), true).toString().getBytes();
114 prevayler.execute(new Transaction() {
115 public void executeOn(Object o, Date now) {
116 Cache cache = (Cache)o;
117 synchronized(cache) {
118 Entry.this.uid = cache.uidNext(true);
119 cache.linear.add(Entry.this);
120 cache.byuid.put(Entry.this.uid, Entry.this);
121 cache.byname.put(Entry.this.name, Entry.this);
125 public int uid() { return uid; }
126 public boolean seen() { return seen; }
127 public void seen(Cache cache, boolean seen) {
129 String base = cache.dir.getParent() + slash + name;
130 File target = new File(base);
131 if (!target.exists()) target = new File(base + "s");
132 target.setLastModified(seen ? MAGIC_DATE : System.currentTimeMillis());
134 public void delete(Cache cache) {
135 String base = cache.dir.getParent() + slash + name;
136 File target = new File(base);
137 if (!target.exists()) target = new File(base + "s");
138 if (target.exists()) target.delete();
140 public Message message(Cache cache) { try {
141 String base = cache.dir.getParent() + slash + name;
142 File target = new File(base);
143 if (!target.exists()) target = new File(base + "s");
144 FileInputStream fis = null;
146 fis = new FileInputStream(target);
147 return new Message(new Stream(fis), new Message.Envelope(null, null, new Date(target.lastModified())));
148 } finally { if (fis != null) fis.close(); }
149 } catch (IOException e) { throw new MailException.IOException(e);
150 } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
155 private static void rmDashRf(File f) throws IOException {
156 if (!f.isDirectory()) { f.delete(); return; }
157 String[] children = f.list();
158 for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
162 private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
167 lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
168 if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
170 File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
172 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
173 cache = (Cache)prevayler.prevalentSystem();
174 } catch (Throwable t) {
175 Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
177 Log.warn(this, "discarding cache...");
179 prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
180 cache = (Cache)prevayler.prevalentSystem();
182 cache.init(prevayler);
186 public Mailbox.Iterator iterator() { return new Iterator(); }
187 public int uidValidity() { return cache.uidValidity; }
188 public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
189 public String[] children() {
191 String[] list = path.list();
192 for(int i=0; i<list.length; i++) {
193 File f = new File(path.getAbsolutePath() + slash + list[i]);
194 if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
196 return (String[])vec.copyInto(new String[vec.size()]);
199 public int uidNext() { return cache.uidNext(false); }
200 public synchronized void add(Message message, int flags) {
201 Log.info(path, message.summary());
203 String name; String fullname; File target; File f;
205 name = cache.uidNext(true) + ".";
206 fullname = path.getAbsolutePath() + slash + name;
207 target = new File(fullname);
208 f = new File(target.getCanonicalPath() + "-");
209 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
210 } while (f.exists() || target.exists());
211 FileOutputStream fo = new FileOutputStream(f);
212 Stream stream = new Stream(fo);
213 if (message.envelope != null) {
214 stream.println("X-org.ibex.mail.headers.envelope.From: " + message.envelope.from);
215 stream.println("X-org.ibex.mail.headers.envelope.To: " + message.envelope.to);
217 message.dump(stream);
219 f.renameTo(new File(fullname));
220 if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
221 new Cache.Entry(cache, prevayler, name);
222 } catch (IOException e) { throw new MailException.IOException(e); }
225 private class Iterator extends Mailbox.Default.Iterator {
227 private Cache.Entry entry() { return cache.getLinear(cur); }
228 public MIME.Headers head() { return done() ? null : entry().headers(); }
229 public boolean done() { return cur >= cache.size(); }
230 public boolean next() { cur++; return !done(); }
231 public boolean seen() { return done() ? false : entry().seen(); }
232 public int num() { return cur+1; } // EUDORA insists that message numbers start at 1, not 0
233 public int uid() { return done() ? -1 : entry().uid(); }
234 public Message cur() { return done() ? null : entry().message(cache); }
235 public void seen(boolean seen) { prevayler.execute(new Seen(uid(), seen)); }
236 public void delete() { if (!done()) prevayler.execute(new Delete(uid())); }
239 private static class Delete implements Transaction {
241 public Delete(int uid) { this.uid = uid; }
242 public void executeOn(Object c, Date d) { ((Cache)c).get(uid).delete((Cache)c); }
244 private static class Seen implements Transaction {
246 private boolean seen;
247 public Seen(int uid, boolean seen) { this.uid = uid; this.seen = seen; }
248 public void executeOn(Object c, Date d) { ((Cache)c).get(uid).seen((Cache)c, seen); }