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