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