util.datamanager: Unreference file handle after closing it to prevent trying to close...
[prosody.git] / util / datamanager.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 local format = string.format;
11 local setmetatable = setmetatable;
12 local ipairs = ipairs;
13 local char = string.char;
14 local pcall = pcall;
15 local log = require "util.logger".init("datamanager");
16 local io_open = io.open;
17 local os_remove = os.remove;
18 local os_rename = os.rename;
19 local tonumber = tonumber;
20 local next = next;
21 local t_insert = table.insert;
22 local t_concat = table.concat;
23 local envloadfile = require"util.envload".envloadfile;
24 local serialize = require "util.serialization".serialize;
25 local path_separator = assert ( package.config:match ( "^([^\n]+)" ) , "package.config not in standard form" ) -- Extract directory seperator from package.config (an undocumented string that comes with lua)
26 local lfs = require "lfs";
27 local prosody = prosody;
28
29 local raw_mkdir = lfs.mkdir;
30 local function fallocate(f, offset, len)
31         -- This assumes that current position == offset
32         local fake_data = (" "):rep(len);
33         local ok, msg = f:write(fake_data);
34         if not ok then
35                 return ok, msg;
36         end
37         f:seek("set", offset);
38         return true;
39 end;
40 pcall(function()
41         local pposix = require "util.pposix";
42         raw_mkdir = pposix.mkdir or raw_mkdir; -- Doesn't trample on umask
43         fallocate = pposix.fallocate or fallocate;
44 end);
45
46 module "datamanager"
47
48 ---- utils -----
49 local encode, decode;
50 do
51         local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
52
53         decode = function (s)
54                 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
55         end
56
57         encode = function (s)
58                 return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end));
59         end
60 end
61
62 local _mkdir = {};
63 local function mkdir(path)
64         path = path:gsub("/", path_separator); -- TODO as an optimization, do this during path creation rather than here
65         if not _mkdir[path] then
66                 raw_mkdir(path);
67                 _mkdir[path] = true;
68         end
69         return path;
70 end
71
72 local data_path = (prosody and prosody.paths and prosody.paths.data) or ".";
73 local callbacks = {};
74
75 ------- API -------------
76
77 function set_data_path(path)
78         log("debug", "Setting data path to: %s", path);
79         data_path = path;
80 end
81
82 local function callback(username, host, datastore, data)
83         for _, f in ipairs(callbacks) do
84                 username, host, datastore, data = f(username, host, datastore, data);
85                 if username == false then break; end
86         end
87
88         return username, host, datastore, data;
89 end
90 function add_callback(func)
91         if not callbacks[func] then -- Would you really want to set the same callback more than once?
92                 callbacks[func] = true;
93                 callbacks[#callbacks+1] = func;
94                 return true;
95         end
96 end
97 function remove_callback(func)
98         if callbacks[func] then
99                 for i, f in ipairs(callbacks) do
100                         if f == func then
101                                 callbacks[i] = nil;
102                                 callbacks[f] = nil;
103                                 return true;
104                         end
105                 end
106         end
107 end
108
109 function getpath(username, host, datastore, ext, create)
110         ext = ext or "dat";
111         host = (host and encode(host)) or "_global";
112         username = username and encode(username);
113         if username then
114                 if create then mkdir(mkdir(mkdir(data_path).."/"..host).."/"..datastore); end
115                 return format("%s/%s/%s/%s.%s", data_path, host, datastore, username, ext);
116         else
117                 if create then mkdir(mkdir(data_path).."/"..host); end
118                 return format("%s/%s/%s.%s", data_path, host, datastore, ext);
119         end
120 end
121
122 function load(username, host, datastore)
123         local data, ret = envloadfile(getpath(username, host, datastore), {});
124         if not data then
125                 local mode = lfs.attributes(getpath(username, host, datastore), "mode");
126                 if not mode then
127                         log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
128                         return nil;
129                 else -- file exists, but can't be read
130                         -- TODO more detailed error checking and logging?
131                         log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
132                         return nil, "Error reading storage";
133                 end
134         end
135
136         local success, ret = pcall(data);
137         if not success then
138                 log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
139                 return nil, "Error reading storage";
140         end
141         return ret;
142 end
143
144 local function atomic_store(filename, data)
145         local scratch = filename.."~";
146         local f, ok, msg;
147         repeat
148                 f, msg = io_open(scratch, "w");
149                 if not f then break end
150
151                 ok, msg = f:write(data);
152                 if not ok then break end
153
154                 ok, msg = f:close();
155                 f = nil; -- no longer valid
156                 if not ok then break end
157
158                 return os_rename(scratch, filename);
159         until false;
160
161         -- Cleanup
162         if f then f:close(); end
163         os_remove(scratch);
164         return nil, msg;
165 end
166
167 if prosody and prosody.platform ~= "posix" then
168         -- os.rename does not overwrite existing files on Windows
169         -- TODO We could use Transactional NTFS on Vista and above
170         function atomic_store(filename, data)
171                 local f, err = io_open(filename, "w");
172                 if not f then return f, err; end
173                 local ok, msg = f:write(data);
174                 if not ok then f:close(); return ok, msg; end
175                 return f:close();
176         end
177 end
178
179 function store(username, host, datastore, data)
180         if not data then
181                 data = {};
182         end
183
184         username, host, datastore, data = callback(username, host, datastore, data);
185         if username == false then
186                 return true; -- Don't save this data at all
187         end
188
189         -- save the datastore
190         local d = "return " .. serialize(data) .. ";\n";
191         local mkdir_cache_cleared;
192         repeat
193                 local ok, msg = atomic_store(getpath(username, host, datastore, nil, true), d);
194                 if not ok then
195                         if not mkdir_cache_cleared then -- We may need to recreate a removed directory
196                                 _mkdir = {};
197                                 mkdir_cache_cleared = true;
198                         else
199                                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
200                                 return nil, "Error saving to storage";
201                         end
202                 end
203                 if next(data) == nil then -- try to delete empty datastore
204                         log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
205                         os_remove(getpath(username, host, datastore));
206                 end
207                 -- we write data even when we are deleting because lua doesn't have a
208                 -- platform independent way of checking for non-exisitng files
209         until ok;
210         return true;
211 end
212
213 function list_append(username, host, datastore, data)
214         if not data then return; end
215         if callback(username, host, datastore) == false then return true; end
216         -- save the datastore
217         local f, msg = io_open(getpath(username, host, datastore, "list", true), "r+");
218         if not f then
219                 f, msg = io_open(getpath(username, host, datastore, "list", true), "w");
220         end
221         if not f then
222                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
223                 return;
224         end
225         local data = "item(" ..  serialize(data) .. ");\n";
226         local pos = f:seek("end");
227         local ok, msg = fallocate(f, pos, #data);
228         f:seek("set", pos);
229         if ok then
230                 f:write(data);
231         else
232                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
233                 return ok, msg;
234         end
235         f:close();
236         return true;
237 end
238
239 function list_store(username, host, datastore, data)
240         if not data then
241                 data = {};
242         end
243         if callback(username, host, datastore) == false then return true; end
244         -- save the datastore
245         local d = {};
246         for _, item in ipairs(data) do
247                 d[#d+1] = "item(" .. serialize(item) .. ");\n";
248         end
249         local ok, msg = atomic_store(getpath(username, host, datastore, "list", true), t_concat(d));
250         if not ok then
251                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
252                 return;
253         end
254         if next(data) == nil then -- try to delete empty datastore
255                 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
256                 os_remove(getpath(username, host, datastore, "list"));
257         end
258         -- we write data even when we are deleting because lua doesn't have a
259         -- platform independent way of checking for non-exisitng files
260         return true;
261 end
262
263 function list_load(username, host, datastore)
264         local items = {};
265         local data, ret = envloadfile(getpath(username, host, datastore, "list"), {item = function(i) t_insert(items, i); end});
266         if not data then
267                 local mode = lfs.attributes(getpath(username, host, datastore, "list"), "mode");
268                 if not mode then
269                         log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
270                         return nil;
271                 else -- file exists, but can't be read
272                         -- TODO more detailed error checking and logging?
273                         log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
274                         return nil, "Error reading storage";
275                 end
276         end
277
278         local success, ret = pcall(data);
279         if not success then
280                 log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
281                 return nil, "Error reading storage";
282         end
283         return items;
284 end
285
286 local type_map = {
287         keyval = "dat";
288         list = "list";
289 }
290
291 function users(host, store, typ)
292         typ = type_map[typ or "keyval"];
293         local store_dir = format("%s/%s/%s", data_path, encode(host), store);
294
295         local mode, err = lfs.attributes(store_dir, "mode");
296         if not mode then
297                 return function() log("debug", "%s", err or (store_dir .. " does not exist")) end
298         end
299         local next, state = lfs.dir(store_dir);
300         return function(state)
301                 for node in next, state do
302                         local file, ext = node:match("^(.*)%.([dalist]+)$");
303                         if file and ext == typ then
304                                 return decode(file);
305                         end
306                 end
307         end, state;
308 end
309
310 function stores(username, host, typ)
311         typ = type_map[typ or "keyval"];
312         local store_dir = format("%s/%s/", data_path, encode(host));
313
314         local mode, err = lfs.attributes(store_dir, "mode");
315         if not mode then
316                 return function() log("debug", err or (store_dir .. " does not exist")) end
317         end
318         local next, state = lfs.dir(store_dir);
319         return function(state)
320                 for node in next, state do
321                         if not node:match"^%." then
322                                 if username == true then
323                                         if lfs.attributes(store_dir..node, "mode") == "directory" then
324                                                 return decode(node);
325                                         end
326                                 elseif username then
327                                         local store = decode(node)
328                                         if lfs.attributes(getpath(username, host, store, typ), "mode") then
329                                                 return store;
330                                         end
331                                 elseif lfs.attributes(node, "mode") == "file" then
332                                         local file, ext = node:match("^(.*)%.([dalist]+)$");
333                                         if ext == typ then
334                                                 return decode(file)
335                                         end
336                                 end
337                         end
338                 end
339         end, state;
340 end
341
342 local function do_remove(path)
343         local ok, err = os_remove(path);
344         if not ok and lfs.attributes(path, "mode") then
345                 return ok, err;
346         end
347         return true
348 end
349
350 function purge(username, host)
351         local host_dir = format("%s/%s/", data_path, encode(host));
352         local ok, iter, state, var = pcall(lfs.dir, host_dir);
353         if not ok then
354                 return ok, iter;
355         end
356         local errs = {};
357         for file in iter, state, var do
358                 if lfs.attributes(host_dir..file, "mode") == "directory" then
359                         local store = decode(file);
360                         local ok, err = do_remove(getpath(username, host, store));
361                         if not ok then errs[#errs+1] = err; end
362
363                         local ok, err = do_remove(getpath(username, host, store, "list"));
364                         if not ok then errs[#errs+1] = err; end
365                 end
366         end
367         return #errs == 0, t_concat(errs, ", ");
368 end
369
370 _M.path_decode = decode;
371 _M.path_encode = encode;
372 return _M;