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;
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;
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);
37 f:seek("set", offset);
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;
51 local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
54 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
58 return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end));
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
72 local data_path = (prosody and prosody.paths and prosody.paths.data) or ".";
75 ------- API -------------
77 local function set_data_path(path)
78 log("debug", "Setting data path to: %s", path);
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
88 return username, host, datastore, data;
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;
97 local function remove_callback(func)
98 if callbacks[func] then
99 for i, f in ipairs(callbacks) do
109 local function getpath(username, host, datastore, ext, create)
111 host = (host and encode(host)) or "_global";
112 username = username and encode(username);
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);
117 if create then mkdir(mkdir(data_path).."/"..host); end
118 return format("%s/%s/%s.%s", data_path, host, datastore, ext);
122 local function load(username, host, datastore)
123 local data, ret = envloadfile(getpath(username, host, datastore), {});
125 local mode = lfs.attributes(getpath(username, host, datastore), "mode");
127 log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "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";
136 local success, ret = pcall(data);
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";
144 local function atomic_store(filename, data)
145 local scratch = filename.."~";
148 f, msg = io_open(scratch, "w");
149 if not f then break end
151 ok, msg = f:write(data);
152 if not ok then break end
155 f = nil; -- no longer valid
156 if not ok then break end
158 return os_rename(scratch, filename);
162 if f then f:close(); end
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
179 local function store(username, host, datastore, data)
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
189 -- save the datastore
190 local d = "return " .. serialize(data) .. ";\n";
191 local mkdir_cache_cleared;
193 local ok, msg = atomic_store(getpath(username, host, datastore, nil, true), d);
195 if not mkdir_cache_cleared then -- We may need to recreate a removed directory
197 mkdir_cache_cleared = true;
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";
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));
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
213 -- Append a blob of data to a file
214 local function append(username, host, datastore, ext, data)
215 if type(data) ~= "string" then return; end
216 local filename = getpath(username, host, datastore, ext, true);
219 local f, msg = io_open(filename, "r+");
221 -- File did probably not exist, let's create it
222 f, msg = io_open(filename, "w");
224 return nil, msg, "open";
228 local pos = f:seek("end");
229 ok, msg = fallocate(f, pos, #data);
231 log("warn", "fallocate() failed: %s", tostring(msg));
232 -- This doesn't work on every file system
235 if f:seek() ~= pos then
236 log("debug", "fallocate() changed file position");
240 ok, msg = f:write(data);
243 return ok, msg, "write";
254 local function list_append(username, host, datastore, data)
255 if not data then return; end
256 if callback(username, host, datastore) == false then return true; end
257 -- save the datastore
259 data = "item(" .. serialize(data) .. ");\n";
260 local ok, msg = append(username, host, datastore, "list", data);
262 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
268 local function list_store(username, host, datastore, data)
272 if callback(username, host, datastore) == false then return true; end
273 -- save the datastore
275 for _, item in ipairs(data) do
276 d[#d+1] = "item(" .. serialize(item) .. ");\n";
278 local ok, msg = atomic_store(getpath(username, host, datastore, "list", true), t_concat(d));
280 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
283 if next(data) == nil then -- try to delete empty datastore
284 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
285 os_remove(getpath(username, host, datastore, "list"));
287 -- we write data even when we are deleting because lua doesn't have a
288 -- platform independent way of checking for non-exisitng files
292 local function list_load(username, host, datastore)
294 local data, ret = envloadfile(getpath(username, host, datastore, "list"), {item = function(i) t_insert(items, i); end});
296 local mode = lfs.attributes(getpath(username, host, datastore, "list"), "mode");
298 log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
300 else -- file exists, but can't be read
301 -- TODO more detailed error checking and logging?
302 log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
303 return nil, "Error reading storage";
307 local success, ret = pcall(data);
309 log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
310 return nil, "Error reading storage";
320 local function users(host, store, typ)
321 typ = type_map[typ or "keyval"];
322 local store_dir = format("%s/%s/%s", data_path, encode(host), store);
324 local mode, err = lfs.attributes(store_dir, "mode");
326 return function() log("debug", "%s", err or (store_dir .. " does not exist")) end
328 local next, state = lfs.dir(store_dir);
329 return function(state)
330 for node in next, state do
331 local file, ext = node:match("^(.*)%.([dalist]+)$");
332 if file and ext == typ then
339 local function stores(username, host, typ)
340 typ = type_map[typ or "keyval"];
341 local store_dir = format("%s/%s/", data_path, encode(host));
343 local mode, err = lfs.attributes(store_dir, "mode");
345 return function() log("debug", err or (store_dir .. " does not exist")) end
347 local next, state = lfs.dir(store_dir);
348 return function(state)
349 for node in next, state do
350 if not node:match"^%." then
351 if username == true then
352 if lfs.attributes(store_dir..node, "mode") == "directory" then
356 local store = decode(node)
357 if lfs.attributes(getpath(username, host, store, typ), "mode") then
360 elseif lfs.attributes(node, "mode") == "file" then
361 local file, ext = node:match("^(.*)%.([dalist]+)$");
371 local function do_remove(path)
372 local ok, err = os_remove(path);
373 if not ok and lfs.attributes(path, "mode") then
379 local function purge(username, host)
380 local host_dir = format("%s/%s/", data_path, encode(host));
381 local ok, iter, state, var = pcall(lfs.dir, host_dir);
386 for file in iter, state, var do
387 if lfs.attributes(host_dir..file, "mode") == "directory" then
388 local store = decode(file);
389 local ok, err = do_remove(getpath(username, host, store));
390 if not ok then errs[#errs+1] = err; end
392 local ok, err = do_remove(getpath(username, host, store, "list"));
393 if not ok then errs[#errs+1] = err; end
396 return #errs == 0, t_concat(errs, ", ");
400 set_data_path = set_data_path;
401 add_callback = add_callback;
402 remove_callback = remove_callback;
407 list_append = list_append;
408 list_store = list_store;
409 list_load = list_load;
413 path_decode = decode;
414 path_encode = encode;