dc98bd13fd3bfd9a0dd0aa9f347dd181bc81a2c9
[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 local _ENV = nil;
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 local 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 local 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 local 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 local 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 local 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
148         f, msg = io_open(scratch, "w");
149         if not f then
150                 return nil, msg;
151         end
152
153         ok, msg = f:write(data);
154         if not ok then
155                 f:close();
156                 os_remove(scratch);
157                 return nil, msg;
158         end
159
160         ok, msg = f:close();
161         if not ok then
162                 os_remove(scratch);
163                 return nil, msg;
164         end
165
166         return os_rename(scratch, filename);
167 end
168
169 if prosody and prosody.platform ~= "posix" then
170         -- os.rename does not overwrite existing files on Windows
171         -- TODO We could use Transactional NTFS on Vista and above
172         function atomic_store(filename, data)
173                 local f, err = io_open(filename, "w");
174                 if not f then return f, err; end
175                 local ok, msg = f:write(data);
176                 if not ok then f:close(); return ok, msg; end
177                 return f:close();
178         end
179 end
180
181 local function store(username, host, datastore, data)
182         if not data then
183                 data = {};
184         end
185
186         username, host, datastore, data = callback(username, host, datastore, data);
187         if username == false then
188                 return true; -- Don't save this data at all
189         end
190
191         -- save the datastore
192         local d = "return " .. serialize(data) .. ";\n";
193         local mkdir_cache_cleared;
194         repeat
195                 local ok, msg = atomic_store(getpath(username, host, datastore, nil, true), d);
196                 if not ok then
197                         if not mkdir_cache_cleared then -- We may need to recreate a removed directory
198                                 _mkdir = {};
199                                 mkdir_cache_cleared = true;
200                         else
201                                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
202                                 return nil, "Error saving to storage";
203                         end
204                 end
205                 if next(data) == nil then -- try to delete empty datastore
206                         log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
207                         os_remove(getpath(username, host, datastore));
208                 end
209                 -- we write data even when we are deleting because lua doesn't have a
210                 -- platform independent way of checking for non-exisitng files
211         until ok;
212         return true;
213 end
214
215 -- Append a blob of data to a file
216 local function append(username, host, datastore, ext, data)
217         if type(data) ~= "string" then return; end
218         local filename = getpath(username, host, datastore, ext, true);
219
220         local ok;
221         local f, msg = io_open(filename, "r+");
222         if not f then
223                 -- File did probably not exist, let's create it
224                 f, msg = io_open(filename, "w");
225                 if not f then
226                         return nil, msg, "open";
227                 end
228         end
229
230         local pos = f:seek("end");
231         ok, msg = fallocate(f, pos, #data);
232         if not ok then
233                 log("warn", "fallocate() failed: %s", tostring(msg));
234                 -- This doesn't work on every file system
235         end
236
237         if f:seek() ~= pos then
238                 log("debug", "fallocate() changed file position");
239                 f:seek("set", pos);
240         end
241
242         ok, msg = f:write(data);
243         if not ok then
244                 f:close();
245                 return ok, msg, "write";
246         end
247
248         ok, msg = f:close();
249         if not ok then
250                 return ok, msg;
251         end
252
253         return true, pos;
254 end
255
256 local function list_append(username, host, datastore, data)
257         if not data then return; end
258         if callback(username, host, datastore) == false then return true; end
259         -- save the datastore
260
261         data = "item(" ..  serialize(data) .. ");\n";
262         local ok, msg = append(username, host, datastore, "list", data);
263         if not ok then
264                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
265                 return ok, msg;
266         end
267         return true;
268 end
269
270 local function list_store(username, host, datastore, data)
271         if not data then
272                 data = {};
273         end
274         if callback(username, host, datastore) == false then return true; end
275         -- save the datastore
276         local d = {};
277         for _, item in ipairs(data) do
278                 d[#d+1] = "item(" .. serialize(item) .. ");\n";
279         end
280         local ok, msg = atomic_store(getpath(username, host, datastore, "list", true), t_concat(d));
281         if not ok then
282                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
283                 return;
284         end
285         if next(data) == nil then -- try to delete empty datastore
286                 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
287                 os_remove(getpath(username, host, datastore, "list"));
288         end
289         -- we write data even when we are deleting because lua doesn't have a
290         -- platform independent way of checking for non-exisitng files
291         return true;
292 end
293
294 local function list_load(username, host, datastore)
295         local items = {};
296         local data, ret = envloadfile(getpath(username, host, datastore, "list"), {item = function(i) t_insert(items, i); end});
297         if not data then
298                 local mode = lfs.attributes(getpath(username, host, datastore, "list"), "mode");
299                 if not mode then
300                         log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
301                         return nil;
302                 else -- file exists, but can't be read
303                         -- TODO more detailed error checking and logging?
304                         log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
305                         return nil, "Error reading storage";
306                 end
307         end
308
309         local success, ret = pcall(data);
310         if not success then
311                 log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
312                 return nil, "Error reading storage";
313         end
314         return items;
315 end
316
317 local type_map = {
318         keyval = "dat";
319         list = "list";
320 }
321
322 local function users(host, store, typ)
323         typ = type_map[typ or "keyval"];
324         local store_dir = format("%s/%s/%s", data_path, encode(host), store);
325
326         local mode, err = lfs.attributes(store_dir, "mode");
327         if not mode then
328                 return function() log("debug", "%s", err or (store_dir .. " does not exist")) end
329         end
330         local next, state = lfs.dir(store_dir);
331         return function(state)
332                 for node in next, state do
333                         local file, ext = node:match("^(.*)%.([dalist]+)$");
334                         if file and ext == typ then
335                                 return decode(file);
336                         end
337                 end
338         end, state;
339 end
340
341 local function stores(username, host, typ)
342         typ = type_map[typ or "keyval"];
343         local store_dir = format("%s/%s/", data_path, encode(host));
344
345         local mode, err = lfs.attributes(store_dir, "mode");
346         if not mode then
347                 return function() log("debug", err or (store_dir .. " does not exist")) end
348         end
349         local next, state = lfs.dir(store_dir);
350         return function(state)
351                 for node in next, state do
352                         if not node:match"^%." then
353                                 if username == true then
354                                         if lfs.attributes(store_dir..node, "mode") == "directory" then
355                                                 return decode(node);
356                                         end
357                                 elseif username then
358                                         local store = decode(node)
359                                         if lfs.attributes(getpath(username, host, store, typ), "mode") then
360                                                 return store;
361                                         end
362                                 elseif lfs.attributes(node, "mode") == "file" then
363                                         local file, ext = node:match("^(.*)%.([dalist]+)$");
364                                         if ext == typ then
365                                                 return decode(file)
366                                         end
367                                 end
368                         end
369                 end
370         end, state;
371 end
372
373 local function do_remove(path)
374         local ok, err = os_remove(path);
375         if not ok and lfs.attributes(path, "mode") then
376                 return ok, err;
377         end
378         return true
379 end
380
381 local function purge(username, host)
382         local host_dir = format("%s/%s/", data_path, encode(host));
383         local ok, iter, state, var = pcall(lfs.dir, host_dir);
384         if not ok then
385                 return ok, iter;
386         end
387         local errs = {};
388         for file in iter, state, var do
389                 if lfs.attributes(host_dir..file, "mode") == "directory" then
390                         local store = decode(file);
391                         local ok, err = do_remove(getpath(username, host, store));
392                         if not ok then errs[#errs+1] = err; end
393
394                         local ok, err = do_remove(getpath(username, host, store, "list"));
395                         if not ok then errs[#errs+1] = err; end
396                 end
397         end
398         return #errs == 0, t_concat(errs, ", ");
399 end
400
401 return {
402         set_data_path = set_data_path;
403         add_callback = add_callback;
404         remove_callback = remove_callback;
405         getpath = getpath;
406         load = load;
407         store = store;
408         append_raw = append;
409         list_append = list_append;
410         list_store = list_store;
411         list_load = list_load;
412         users = users;
413         stores = stores;
414         purge = purge;
415         path_decode = decode;
416         path_encode = encode;
417 };