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, type = setmetatable, type;
12 local pairs, ipairs = pairs, 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 tostring, tonumber = tostring, tonumber;
21 local t_insert = table.insert;
22 local append = require "util.serialization".append;
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;
31 if prosody.platform == "posix" then
32 raw_mkdir = require "util.pposix".mkdir; -- Doesn't trample on umask
33 fallocate = require "util.pposix".fallocate;
35 raw_mkdir = lfs.mkdir;
38 if not fallocate then -- Fallback
39 function fallocate(f, offset, len)
40 -- This assumes that current position == offset
41 local fake_data = (" "):rep(len);
42 local ok, msg = f:write(fake_data);
56 local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
59 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
63 return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end));
68 local function mkdir(path)
69 path = path:gsub("/", path_separator); -- TODO as an optimization, do this during path creation rather than here
70 if not _mkdir[path] then
77 local data_path = (prosody and prosody.paths and prosody.paths.data) or ".";
80 ------- API -------------
82 function set_data_path(path)
83 log("debug", "Setting data path to: %s", path);
87 local function callback(username, host, datastore, data)
88 for _, f in ipairs(callbacks) do
89 username, host, datastore, data = f(username, host, datastore, data);
90 if username == false then break; end
93 return username, host, datastore, data;
95 function add_callback(func)
96 if not callbacks[func] then -- Would you really want to set the same callback more than once?
97 callbacks[func] = true;
98 callbacks[#callbacks+1] = func;
102 function remove_callback(func)
103 if callbacks[func] then
104 for i, f in ipairs(callbacks) do
114 function getpath(username, host, datastore, ext, create)
116 host = (host and encode(host)) or "_global";
117 username = username and encode(username);
119 if create then mkdir(mkdir(mkdir(data_path).."/"..host).."/"..datastore); end
120 return format("%s/%s/%s/%s.%s", data_path, host, datastore, username, ext);
122 if create then mkdir(mkdir(data_path).."/"..host); end
123 return format("%s/%s/%s.%s", data_path, host, datastore, ext);
125 if create then mkdir(data_path); end
126 return format("%s/%s.%s", data_path, datastore, ext);
130 function load(username, host, datastore)
131 local data, ret = envloadfile(getpath(username, host, datastore), {});
133 local mode = lfs.attributes(getpath(username, host, datastore), "mode");
135 log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
137 else -- file exists, but can't be read
138 -- TODO more detailed error checking and logging?
139 log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
140 return nil, "Error reading storage";
144 local success, ret = pcall(data);
146 log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
147 return nil, "Error reading storage";
152 function store(username, host, datastore, data)
157 username, host, datastore, data = callback(username, host, datastore, data);
158 if username == false then
159 return true; -- Don't save this data at all
162 -- save the datastore
163 local f, msg = io_open(getpath(username, host, datastore, nil, true), "w+");
165 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
166 return nil, "Error saving to storage";
171 if next(data) == nil then -- try to delete empty datastore
172 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
173 os_remove(getpath(username, host, datastore));
175 -- we write data even when we are deleting because lua doesn't have a
176 -- platform independent way of checking for non-exisitng files
180 function list_append(username, host, datastore, data)
181 if not data then return; end
182 if callback(username, host, datastore) == false then return true; end
183 -- save the datastore
184 local f, msg = io_open(getpath(username, host, datastore, "list", true), "a");
186 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
189 local data = "item(" .. serialize(data) .. ");\n";
190 local pos = f:seek("end");
191 local ok, msg = fallocate(f, pos, #data);
196 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
203 function list_store(username, host, datastore, data)
207 if callback(username, host, datastore) == false then return true; end
208 -- save the datastore
209 local f, msg = io_open(getpath(username, host, datastore, "list", true), "w+");
211 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
214 for _, d in ipairs(data) do
220 if next(data) == nil then -- try to delete empty datastore
221 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
222 os_remove(getpath(username, host, datastore, "list"));
224 -- we write data even when we are deleting because lua doesn't have a
225 -- platform independent way of checking for non-exisitng files
229 function list_load(username, host, datastore)
231 local data, ret = envloadfile(getpath(username, host, datastore, "list"), {item = function(i) t_insert(items, i); end});
233 local mode = lfs.attributes(getpath(username, host, datastore, "list"), "mode");
235 log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
237 else -- file exists, but can't be read
238 -- TODO more detailed error checking and logging?
239 log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
240 return nil, "Error reading storage";
244 local success, ret = pcall(data);
246 log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
247 return nil, "Error reading storage";
252 function list_stores(username, host)
254 return nil, "bad argument #2 to 'list_stores' (string expected, got nothing)";
257 local host_dir = format("%s/%s/", data_path, encode(host));
258 for node in lfs.dir(host_dir) do
259 if not node:match"^%." then -- dots should be encoded, this is probably . or ..
260 local store = decode(node);
261 local path = host_dir..node;
262 if username == true then
263 if lfs.attributes(path, "mode") == "directory" then
264 list[#list+1] = store;
267 if lfs.attributes(getpath(username, host, store), "mode")
268 or lfs.attributes(getpath(username, host, store, "list"), "mode") then
269 list[#list+1] = store;
271 elseif lfs.attributes(path, "mode") == "file" then
272 list[#list+1] = store:gsub("%.[dalist]+$","");
279 function purge(username, host)
280 local host_dir = format("%s/%s/", data_path, encode(host));
282 for file in lfs.dir(host_dir) do
283 if lfs.attributes(host_dir..file, "mode") == "directory" then
284 local store = decode(file);
285 deleted = deleted + (os_remove(getpath(username, host, store)) and 1 or 0);
286 deleted = deleted + (os_remove(getpath(username, host, store, "list")) and 1 or 0);
287 -- We this will generate loads of "No such file or directory", but do we care?
290 return deleted > 0, deleted;