2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
10 local format = string.format;
11 local setmetatable = setmetatable;
12 local ipairs = ipairs;
13 local char = string.char;
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;
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;
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);
39 f:seek("set", offset);
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;
53 local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
56 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
60 return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end));
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
74 local data_path = (prosody and prosody.paths and prosody.paths.data) or ".";
77 ------- API -------------
79 local function set_data_path(path)
80 log("debug", "Setting data path to: %s", path);
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
90 return username, host, datastore, data;
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;
99 local function remove_callback(func)
100 if callbacks[func] then
101 for i, f in ipairs(callbacks) do
111 local function getpath(username, host, datastore, ext, create)
113 host = (host and encode(host)) or "_global";
114 username = username and encode(username);
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);
119 if create then mkdir(mkdir(data_path).."/"..host); end
120 return format("%s/%s/%s.%s", data_path, host, datastore, ext);
124 local function load(username, host, datastore)
125 local data, ret = envloadfile(getpath(username, host, datastore), {});
127 local mode = lfs.attributes(getpath(username, host, datastore), "mode");
129 log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "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";
138 local success, ret = pcall(data);
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";
146 local function atomic_store(filename, data)
147 local scratch = filename.."~";
150 f, msg = io_open(scratch, "w");
155 ok, msg = f:write(data);
168 return os_rename(scratch, filename);
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
183 local function store(username, host, datastore, data)
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
193 -- save the datastore
194 local d = "return " .. serialize(data) .. ";\n";
195 local mkdir_cache_cleared;
197 local ok, msg = atomic_store(getpath(username, host, datastore, nil, true), d);
199 if not mkdir_cache_cleared then -- We may need to recreate a removed directory
201 mkdir_cache_cleared = true;
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";
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));
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
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);
223 local f, msg = io_open(filename, "r+");
225 -- File did probably not exist, let's create it
226 f, msg = io_open(filename, "w");
228 return nil, msg, "open";
232 local pos = f:seek("end");
233 ok, msg = fallocate(f, pos, #data);
235 log("warn", "fallocate() failed: %s", tostring(msg));
236 -- This doesn't work on every file system
239 if f:seek() ~= pos then
240 log("debug", "fallocate() changed file position");
244 ok, msg = f:write(data);
247 return ok, msg, "write";
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
263 data = "item(" .. serialize(data) .. ");\n";
264 local ok, msg = append(username, host, datastore, "list", data);
266 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
272 local function list_store(username, host, datastore, data)
276 if callback(username, host, datastore) == false then return true; end
277 -- save the datastore
279 for _, item in ipairs(data) do
280 d[#d+1] = "item(" .. serialize(item) .. ");\n";
282 local ok, msg = atomic_store(getpath(username, host, datastore, "list", true), t_concat(d));
284 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
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"));
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
296 local function list_load(username, host, datastore)
298 local data, ret = envloadfile(getpath(username, host, datastore, "list"), {item = function(i) t_insert(items, i); end});
300 local mode = lfs.attributes(getpath(username, host, datastore, "list"), "mode");
302 log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "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";
311 local success, ret = pcall(data);
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";
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);
328 local mode, err = lfs.attributes(store_dir, "mode");
330 return function() log("debug", "%s", err or (store_dir .. " does not exist")) 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
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));
347 local mode, err = lfs.attributes(store_dir, "mode");
349 return function() log("debug", err or (store_dir .. " does not exist")) 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
360 local store = decode(node)
361 if lfs.attributes(getpath(username, host, store, typ), "mode") then
364 elseif lfs.attributes(node, "mode") == "file" then
365 local file, ext = node:match("^(.*)%.([dalist]+)$");
375 local function do_remove(path)
376 local ok, err = os_remove(path);
377 if not ok and lfs.attributes(path, "mode") then
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);
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
396 local ok, err = do_remove(getpath(username, host, store, "list"));
397 if not ok then errs[#errs+1] = err; end
400 return #errs == 0, t_concat(errs, ", ");
404 set_data_path = set_data_path;
405 add_callback = add_callback;
406 remove_callback = remove_callback;
411 list_append = list_append;
412 list_store = list_store;
413 list_load = list_load;
417 path_decode = decode;
418 path_encode = encode;