only use positive integers for uidvalidity
[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     private static final char slash = File.separatorChar;
19     private static final WeakHashMap<String,FileBasedMailbox> instances = new WeakHashMap<String,FileBasedMailbox>();
20     public String toString() { return "[FileBasedMailbox " + path.getAbsolutePath() + "]"; }
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 = Math.abs(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
60             // Drop entries whose files have vanished
61             ArrayList<Transaction> kill = new ArrayList<Transaction>();
62             for(String s : byname.keySet())
63                 if (!new File(dir.getParent() + slash + s).exists())
64                     kill.add(byname.get(s).delete(null));
65             for(Transaction t : kill) prevayler.execute(t);
66
67             // Make entries for new files which have appeared
68             for(String file : new File(dir.getParent()).list()) {
69                 File f = new File(dir.getParent() + slash + file);
70                 if (file.charAt(0)!='.' && !f.isDirectory()) {
71                     Entry e = get(file);
72                     if (e == null)
73                         prevayler.execute(Entry.create(f));
74                     else if ((f.lastModified() == MAGIC_DATE) != e.seen())
75                         prevayler.execute(e.seen(f, !e.seen()));
76                 }
77             }
78
79             // Take a snapshot for posterity
80             Log.info(this, "  done initializing maildir " + dir.getParent());
81             new Thread() { public void run() {
82                 try { prevayler.takeSnapshot(); } catch (Exception e) { Log.error(this, e); } } }.start();
83         }
84
85        
86         public synchronized int size() { return linear.size(); }
87         public synchronized int uidNext() { return 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) { return byname.get(name); }
91
92         public static class Entry implements Serializable {
93             private final byte[] header;
94             public final String name;
95             public final int uid;
96             private boolean seen;
97             private Entry(String name, boolean seen, int uid, byte[] header) {
98                 this.name = name; this.seen = seen; this.uid = uid; this.header = header; }
99
100             // Accessors //////////////////////////////////////////////////////////////////////////////
101
102             public boolean seen() { return seen; }
103             public MIME.Headers headers() { return new MIME.Headers(new Stream(new ByteArrayInputStream(header)), true); }
104             public Message message(Cache cache) { try {
105                 FileInputStream fis = null;
106                 try {
107                     fis = new FileInputStream(cache.dir.getParent() + slash + name);
108                     return new Message(new Stream(fis), new Message.Envelope(null, null, new Date()));
109                 } finally { if (fis != null) fis.close(); }
110             } catch (IOException e) { throw new MailException.IOException(e);
111             } catch (Message.Malformed e) { throw new MailException(e.getMessage()); }
112             }
113
114             // Transactions //////////////////////////////////////////////////////////////////////////////
115
116             public static Transaction create(File f) throws IOException {
117                 final boolean seen = f.lastModified() == MAGIC_DATE;
118                 Log.error(Entry.class, "create with seen = " + seen);
119                 final String name = f.getName();
120                 final byte[] header = new MIME.Headers(new Stream(new FileInputStream(f)), true).toString().getBytes();
121                 return new Transaction() {
122                         public void executeOn(Object o, Date now) {
123                             Cache cache = (Cache)o;
124                             synchronized(cache) {
125                                 Entry e = new Entry(name, seen, cache.uidNext++, header);
126                                 cache.linear.add(e);
127                                 cache.byuid.put(e.uid, e);
128                                 cache.byname.put(e.name, e);
129                             } } };
130             }
131
132             public Transaction seen(File f, final boolean seen) {
133                 f.setLastModified(seen ? MAGIC_DATE : System.currentTimeMillis());
134                 final int uid = this.uid;
135                 return new Transaction() {
136                         public void executeOn(Object o, Date now) {
137                             Cache cache = (Cache)o;
138                             synchronized(cache) {
139                                 cache.get(uid).seen = seen;
140                             } } };
141             }
142             public Transaction delete(File f) {
143                 if (f != null && f.exists()) f.delete();
144                 final int uid = this.uid;
145                 return new Transaction() {
146                         public void executeOn(Object o, Date now) {
147                             Cache cache = (Cache)o;
148                             synchronized(cache) {
149                                 Cache.Entry e = cache.get(uid);
150                                 cache.byname.remove(e.name);
151                                 cache.linear.remove(e);
152                                 cache.byuid.remove(uid);
153                             } } };
154             }
155         }
156     }
157
158     // Helpers //////////////////////////////////////////////////////////////////////////////
159
160     private static void rmDashRf(File f) throws IOException {
161         if (!f.isDirectory()) { f.delete(); return; }
162         String[] children = f.list();
163         for(int i=0; i<children.length; i++) rmDashRf(new File(f.getAbsolutePath() + slash + children[i]));
164         f.delete();
165     }
166
167     private FileBasedMailbox(File path) throws MailException, IOException, ClassNotFoundException {
168         this.path = path;
169         path.mkdirs();
170
171         // acquire lock
172         lock = new RandomAccessFile(this.path.getAbsolutePath() + slash + ".lock", "rw").getChannel().tryLock();
173         if (lock == null) throw new IOException("unable to lock FileBasedMailbox");
174
175         File cacheDir = new File(path.getAbsolutePath() + slash + ".cache");
176         try {
177             prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
178             cache = (Cache)prevayler.prevalentSystem();
179         } catch (Throwable t) {
180             Log.warn(this, "error while attempting to reconstitute a FileBasedMailbox.cache:");
181             Log.warn(this, t);
182             Log.warn(this, "discarding cache...");
183             rmDashRf(cacheDir);
184             prevayler = PrevaylerFactory.createPrevayler(new Cache(cacheDir), cacheDir.getAbsolutePath());
185             cache = (Cache)prevayler.prevalentSystem();
186         }
187         cache.init(prevayler);
188     }
189
190
191     public Mailbox.Iterator  iterator()           { return new Iterator(); }
192     public int               uidValidity()        { return cache.uidValidity; }
193     public synchronized void add(Message message) { add(message, Mailbox.Flag.RECENT); }
194     public String[] children() {
195         Vec vec = new Vec();
196         String[] list = path.list();
197         for(int i=0; i<list.length; i++) {
198             File f = new File(path.getAbsolutePath() + slash + list[i]);
199             if (f.isDirectory() && f.getName().charAt(0) != '.') vec.addElement(list[i]);
200         }
201         return (String[])vec.copyInto(new String[vec.size()]);
202     }
203
204     public int uidNext() { return cache.uidNext(); }
205     public synchronized void add(Message message, int flags) {
206         Log.info(path, message.summary());
207         try {
208             String name, fullname; File target, f;
209             for(int i = cache.uidNext(); ; i++) {
210                 name = i + ".";
211                 fullname = path.getAbsolutePath() + slash + name;
212                 target = new File(fullname);
213                 f = new File(target.getCanonicalPath() + "-");
214                 if (!f.exists() && !target.exists()) break;
215                 Log.error(this, "aieeee!!!! target of add() already exists: " + target.getAbsolutePath());
216             }
217             FileOutputStream fo = new FileOutputStream(f);
218             Stream stream = new Stream(fo);
219             if (message.envelope != null) {
220                 stream.println("X-org.ibex.mail.headers.envelope.From: " + message.envelope.from);
221                 stream.println("X-org.ibex.mail.headers.envelope.To: " + message.envelope.to);
222             }
223             message.dump(stream);
224             fo.close();
225             f.renameTo(new File(fullname));
226             f = new File(fullname);
227             if ((flags & Mailbox.Flag.SEEN) == Mailbox.Flag.SEEN) f.setLastModified(MAGIC_DATE);
228             prevayler.execute(Cache.Entry.create(f));
229         } catch (IOException e) { throw new MailException.IOException(e); }
230     }
231
232     private class Iterator extends Mailbox.Default.Iterator {
233         int cur = -1;
234         private Cache.Entry entry() { return cache.getLinear(cur); }
235         private File file() { return new File(cache.dir.getParent() + slash + entry().name); }
236         public MIME.Headers head() { return done() ? null : entry().headers(); }
237         public boolean done() { return cur >= cache.size(); }
238         public boolean next() { cur++; return !done(); }
239         public boolean seen() { return done() ? false : entry().seen(); }
240         public int num() { return cur+1; }  // EUDORA insists that message numbers start at 1, not 0
241         public int uid() { return done() ? -1 : entry().uid; }
242         public void delete() { prevayler.execute(entry().delete(file())); }
243         public void seen(boolean seen) { prevayler.execute(entry().seen(file(), seen)); }
244         public Message cur() { return entry().message(cache); }
245     }
246
247 }