more fixups to FileBasedMailbox (sigh)
[org.ibex.mail.git] / src / org / ibex / mail / target / FileBasedMailbox.java
1 package org.ibex.mail.target;
2 import org.prevayler.*;
3 import org.ibex.mail.*;
4 import org.ibex.util.*;
5 import org.ibex.io.*;
6 import java.io.*;
7 import java.nio.*;
8 import java.nio.channels.*;
9 import java.net.*;
10 import java.util.*;
11 import java.text.*;
12
13 /** An exceptionally crude implementation of Mailbox relying on POSIXy filesystem semantics */
14 public class FileBasedMailbox extends Mailbox.Default {
15
16     public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
17     private static final char slash = File.separatorChar;
18     private static final WeakHashMap<String,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
19     public Mailbox slash(String name, boolean create) { return getFileBasedMailbox(path.getAbsolutePath()+slash+name, create); }
20
21     // FIXME: should be a File()
22     public static synchronized FileBasedMailbox getFileBasedMailbox(String path, boolean create) {
23         try {
24             FileBasedMailbox ret = instances.get(path);
25             if (ret == null) {
26                 if (!create && !(new File(path).exists())) return null;
27                 instances.put(path, ret = new FileBasedMailbox(new File(path)));
28             }
29             return ret;
30         } catch (Exception e) {
31             Log.error(FileBasedMailbox.class, e);
32             return null;
33         }
34     }
35
36
37     // Instance //////////////////////////////////////////////////////////////////////////////
38
39     private File path;
40     private FileLock lock;
41     private Prevayler prevayler;
42     private Cache cache;
43
44     public static class Cache implements Serializable {
45         public            final int uidValidity = new Random().nextInt();
46         private           final Hashtable<String,Entry> byname = new Hashtable<String,Entry>();
47         private           final Hashtable<Integer,Entry> byuid = new Hashtable<Integer,Entry>();
48         private           final ArrayList<Entry>        linear = new ArrayList<Entry>();
49         public            final File dir;
50         private                 int uidNext = 0;
51
52         public Cache(File dir) { this.dir = dir; }
53
54         public void init(Prevayler prevayler) throws IOException {
55             dir.mkdirs();
56             Log.info(this, "initializing maildir " + dir.getParent());
57             boolean invalid = false;
58             ArrayList<Transaction> kill = new ArrayList<Transaction>();
59             for(String s : byname.keySet()) {
60                 String name = dir.getParent() + slash + s;
61                 if (!new File(name).exists() && !new File(name+"s").exists()) {
62                     Log.error(this, "dropping message " + name);
63                     kill.add(new Drop(byname.get(s).uid()));
64                 }
65             }
66             for(Transaction t : kill) prevayler.execute(t);
67             for(String file : new File(dir.getParent()).list())
68                 if (file.charAt(0)!='.' && !(new File(dir.getParent() + slash + file).isDirectory()))
69                     if (get(file) == null) new Entry(this, prevayler, file);
70             Log.info(this, "  done initializing maildir " + dir.getParent());
71             prevayler.takeSnapshot();
72         }
73
74         public static class Drop implements Transaction {
75             int uid;
76             public Drop(int uid) { this.uid = uid; }
77             public void executeOn(Object o, Date now) {
78                 Cache c = (Cache)o;
79                 Entry e = c.get(uid);
80                 c.byname.remove(e.name);
81                 c.linear.remove(e);
82                 c.byuid.remove(uid);
83             } 
84         }
85         
86         public synchronized int size() { return linear.size(); }
87         public synchronized int uidNext(boolean increment) { return increment ? uidNext++ : uidNext; }
88         public synchronized Entry get(int uid) { return byuid.get(uid); }
89         public synchronized Entry getLinear(int num) { return linear.get(num); }
90         public synchronized Entry get(String name) {
91             if (name.endsWith("s")) name = name.substring(0, name.length() - 1);
92             return byname.get(name);
93         }
94
95         public static class Entry implements Serializable {
96             public final MIME.Headers headers;
97             public final String name;
98             private int uid;
99             private boolean seen;
100             
101             public Entry(Cache cache, Prevayler prevayler, String name) throws IOException {
102                 seen = name.endsWith("s");
103                 this.name = seen ? name.substring(0, name.length() - 1) : name;
104                 headers = new MIME.Headers(new Stream(new FileInputStream(cache.dir.getParent()+slash+name)), true);
105                 prevayler.execute(new Transaction() {
106                         public void executeOn(Object o, Date now) {
107                             Cache cache = (Cache)o;
108                             synchronized(cache) {
109                                 Entry.this.uid = cache.uidNext(true);
110                                 cache.linear.add(Entry.this);
111                                 cache.byuid.put(Entry.this.uid, Entry.this);
112                                 cache.byname.put(Entry.this.name, Entry.this);
113                             } } });
114             }
115
116             public int uid() { return uid; }
117             public boolean seen() { return seen; }
118             public void seen(Cache cache, boolean seen) {
119                 String base = cache.dir.getParent() + slash + name;
120                 File target = new File(base + (seen?"s":""));
121                 this.seen = seen;
122                 if (target.exists()) return;
123                 new File(base + (seen?"":"s")).renameTo(target);
124             }
125             public void delete(Cache cache) {
126                 String base = cache.dir.getParent() + slash + name;
127                 File target = new File(base);
128                 if (!target.exists()) target = new File(base + "s");
129                 if (target.exists()) target.delete();
130             }
131             public Message message(Cache cache) { try {
132                 String base = cache.dir.getParent() + slash + name;
133                 File target = new File(base);
134                 if (!target.exists()) target = new File(base + "s");
135                 FileInputStream fis = null;
136                 try {
137                     fis = new FileInputStream(target);
138                     return new Message(new Stream(fis), new Message.Envelope(null, null, new Date(target.lastModified())));
139                 } finally { if (fis != null) fis.close(); }
140             } catch (IOException e) { throw new MailException.IOException(e);
141             } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
142             }
143         }
144     }
145
146     private static void rmDashRf(File f) throws IOException {
147         if (!f.isDirectory()) { f.delete(); return; }
148         String[] children = f.list();
149         for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
150         f.delete();
151     }
152
153     private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
154         this.path = path;
155         path.mkdirs();
156
157         // acquire lock
158         lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
159         if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
160
161         File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
162         try {
163             prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
164             cache = (Cache)prevayler.prevalentSystem();
165         } catch (Throwable t) {
166             Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
167             Log.warn(this, t);
168             Log.warn(this, "discarding cache...");
169             rmDashRf(cacheDir);
170             prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
171             cache = (Cache)prevayler.prevalentSystem();
172         }
173         cache.init(prevayler);
174     }
175
176
177     public Mailbox.Iterator  iterator()           { return new Iterator(); }
178     public int               uidValidity()        { return cache.uidValidity; }
179     public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
180     public String[] children() {
181         Vec vec = new Vec();
182         String[] list = path.list();
183         for(int i=0; i<list.length; i++) {
184             File f = new File(path.getAbsolutePath() + slash + list[i]);
185             if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
186         }
187         return (String[])vec.copyInto(new String[vec.size()]);
188     }
189
190     public int uidNext() { return cache.uidNext(false); }
191     public synchronized void add(Message message, int flags) {
192         Log.info(path, message.summary());
193         try {
194             String name; String fullname; File target; File f;
195             do {
196                 name = cache.uidNext(true) + "." + ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN ? "s" : "");
197                 fullname = path.getAbsolutePath() + slash + name;
198                 target = new File(fullname);
199                 f = new File(target.getCanonicalPath() + "-");
200                 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
201             } while (f.exists() || target.exists());
202             FileOutputStream fo = new FileOutputStream(f);
203             Stream stream = new Stream(fo);
204             if (message.envelope != null) {
205                 stream.println("X-org.ibex.mail.headers.envelope.From: " + message.envelope.from);
206                 stream.println("X-org.ibex.mail.headers.envelope.To: " + message.envelope.to);
207             }
208             message.dump(stream);
209             fo.close();
210             f.renameTo(new File(fullname));
211             new Cache.Entry(cache, prevayler, name);
212         } catch (IOException e) { throw new MailException.IOException(e); }
213     }
214
215     private class Iterator extends Mailbox.Default.Iterator {
216         int cur = -1;
217         private Cache.Entry entry() { return cache.getLinear(cur); }
218         public MIME.Headers head() { return done() ? null : entry().headers; }
219         public boolean done() { return cur >= cache.size(); }
220         public boolean next() { cur++; return !done(); }
221         public boolean seen() { return done() ? false : entry().seen(); }
222         public int num() { return cur+1; }  // EUDORA insists that message numbers start at 1, not 0
223         public int uid() { return done() ? -1 : entry().uid(); }
224         public Message cur() { return done() ? null : entry().message(cache); }
225         public void seen(boolean seen) { prevayler.execute(new Seen(uid(), seen)); }
226         public void delete() { prevayler.execute(new Delete(uid())); }
227     }
228
229     private static class Delete implements Transaction {
230         private int uid;
231         public Delete(int uid) { this.uid = uid; }
232         public void executeOn(Object c, Date d) { ((Cache)c).get(uid).delete((Cache)c); }
233     }
234     private static class Seen implements Transaction {
235         private int uid;
236         private boolean seen;
237         public Seen(int uid, boolean seen) { this.uid = uid; this.seen = seen; }
238         public void executeOn(Object c, Date d) { ((Cache)c).get(uid).seen((Cache)c, seen); }
239     }
240 }