util.datamanager: Make the util.pposix dependency optional.
[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 module "datamanager"
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 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 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 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 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         elseif host then
117                 if create then mkdir(mkdir(data_path).."/"..host); end
118                 return format("%s/%s/%s.%s", data_path, host, datastore, ext);
119         else
120                 if create then mkdir(data_path); end
121                 return format("%s/%s.%s", data_path, datastore, ext);
122         end
123 end
124
125 function load(username, host, datastore)
126         local data, ret = envloadfile(getpath(username, host, datastore), {});
127         if not data then
128                 local mode = lfs.attributes(getpath(username, host, datastore), "mode");
129                 if not mode then
130                         log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
131                         return nil;
132                 else -- file exists, but can't be read
133                         -- TODO more detailed error checking and logging?
134                         log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
135                         return nil, "Error reading storage";
136                 end
137         end
138
139         local success, ret = pcall(data);
140         if not success then
141                 log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
142                 return nil, "Error reading storage";
143         end
144         return ret;
145 end
146
147 local function atomic_store(filename, data)
148         local scratch = filename.."~";
149         local f, ok, msg;
150         repeat
151                 f, msg = io_open(scratch, "w");
152                 if not f then break end
153
154                 ok, msg = f:write(data);
155                 if not ok then break end
156
157                 ok, msg = f:close();
158                 if not ok then break end
159
160                 return os_rename(scratch, filename);
161         until false;
162
163         -- Cleanup
164         if f then f:close(); end
165         os_remove(scratch);
166         return nil, msg;
167 end
168
169 if prosody.platform ~= "posix" then
170         -- os.rename does not overwrite existing files on Windows
171         -- TODO We could use Transactional NTFS on Vista and above
172         function atomic_store(filename, data)
173                 local f, err = io_open(filename, "w");
174                 if not f then return f, err; end
175                 local ok, msg = f:write(data);
176                 if not ok then f:close(); return ok, msg; end
177                 return f:close();
178         end
179 end
180
181 function store(username, host, datastore, data)
182         if not data then
183                 data = {};
184         end
185
186         username, host, datastore, data = callback(username, host, datastore, data);
187         if username == false then
188                 return true; -- Don't save this data at all
189         end
190
191         -- save the datastore
192         local d = "return " .. serialize(data) .. ";\n";
193         local ok, msg = atomic_store(getpath(username, host, datastore, nil, true), d);
194         if not ok then
195                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
196                 return nil, "Error saving to storage";
197         end
198         if next(data) == nil then -- try to delete empty datastore
199                 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
200                 os_remove(getpath(username, host, datastore));
201         end
202         -- we write data even when we are deleting because lua doesn't have a
203         -- platform independent way of checking for non-exisitng files
204         return true;
205 end
206
207 function list_append(username, host, datastore, data)
208         if not data then return; end
209         if callback(username, host, datastore) == false then return true; end
210         -- save the datastore
211         local f, msg = io_open(getpath(username, host, datastore, "list", true), "r+");
212         if not f then
213                 f, msg = io_open(getpath(username, host, datastore, "list", true), "w");
214         end
215         if not f then
216                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
217                 return;
218         end
219         local data = "item(" ..  serialize(data) .. ");\n";
220         local pos = f:seek("end");
221         local ok, msg = fallocate(f, pos, #data);
222         f:seek("set", pos);
223         if ok then
224                 f:write(data);
225         else
226                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
227                 return ok, msg;
228         end
229         f:close();
230         return true;
231 end
232
233 function list_store(username, host, datastore, data)
234         if not data then
235                 data = {};
236         end
237         if callback(username, host, datastore) == false then return true; end
238         -- save the datastore
239         local d = {};
240         for _, item in ipairs(data) do
241                 d[#d+1] = "item(" .. serialize(item) .. ");\n";
242         end
243         local ok, msg = atomic_store(getpath(username, host, datastore, "list", true), t_concat(d));
244         if not ok then
245                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
246                 return;
247         end
248         if next(data) == nil then -- try to delete empty datastore
249                 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
250                 os_remove(getpath(username, host, datastore, "list"));
251         end
252         -- we write data even when we are deleting because lua doesn't have a
253         -- platform independent way of checking for non-exisitng files
254         return true;
255 end
256
257 function list_load(username, host, datastore)
258         local items = {};
259         local data, ret = envloadfile(getpath(username, host, datastore, "list"), {item = function(i) t_insert(items, i); end});
260         if not data then
261                 local mode = lfs.attributes(getpath(username, host, datastore, "list"), "mode");
262                 if not mode then
263                         log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
264                         return nil;
265                 else -- file exists, but can't be read
266                         -- TODO more detailed error checking and logging?
267                         log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
268                         return nil, "Error reading storage";
269                 end
270         end
271
272         local success, ret = pcall(data);
273         if not success then
274                 log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
275                 return nil, "Error reading storage";
276         end
277         return items;
278 end
279
280 function list_stores(username, host)
281         if not host then
282                 return nil, "bad argument #2 to 'list_stores' (string expected, got nothing)";
283         end
284         local list = {};
285         local host_dir = format("%s/%s/", data_path, encode(host));
286         for node in lfs.dir(host_dir) do
287                 if not node:match"^%." then -- dots should be encoded, this is probably . or ..
288                         local store = decode(node);
289                         local path = host_dir..node;
290                         if username == true then
291                                 if lfs.attributes(path, "mode") == "directory" then
292                                         list[#list+1] = store;
293                                 end
294                         elseif username then
295                                 if lfs.attributes(getpath(username, host, store), "mode")
296                                         or lfs.attributes(getpath(username, host, store, "list"), "mode") then
297                                         list[#list+1] = store;
298                                 end
299                         elseif lfs.attributes(path, "mode") == "file" then
300                                 list[#list+1] = store:gsub("%.[dalist]+$","");
301                         end
302                 end
303         end
304         return list;
305 end
306
307 local function do_remove(path)
308         local ok, err = os_remove(path);
309         if not ok and lfs.attributes(path, "mode") then
310                 return ok, err;
311         end
312         return true
313 end
314
315 function purge(username, host)
316         local host_dir = format("%s/%s/", data_path, encode(host));
317         local deleted = 0;
318         local errs = {};
319         for file in lfs.dir(host_dir) do
320                 if lfs.attributes(host_dir..file, "mode") == "directory" then
321                         local store = decode(file);
322                         local ok, err = do_remove(getpath(username, host, store));
323                         if not ok then errs[#errs+1] = err; end
324
325                         local ok, err = do_remove(getpath(username, host, store, "list"));
326                         if not ok then errs[#errs+1] = err; end
327                 end
328         end
329         return #errs == 0, t_concat(errs, ", ");
330 end
331
332 return _M;