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