util.datamanager: Try to open in read+write mode, then retry with write mode if that...
[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 local raw_mkdir;
29 local fallocate;
30
31 if prosody.platform == "posix" then
32         raw_mkdir = require "util.pposix".mkdir; -- Doesn't trample on umask
33         fallocate = require "util.pposix".fallocate;
34 else
35         raw_mkdir = lfs.mkdir;
36 end
37
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);
43                 if not ok then
44                         return ok, msg;
45                 end
46                 f:seek("set", offset);
47                 return true;
48         end
49 end
50
51 module "datamanager"
52
53 ---- utils -----
54 local encode, decode;
55 do
56         local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
57
58         decode = function (s)
59                 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
60         end
61
62         encode = function (s)
63                 return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end));
64         end
65 end
66
67 local _mkdir = {};
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
71                 raw_mkdir(path);
72                 _mkdir[path] = true;
73         end
74         return path;
75 end
76
77 local data_path = (prosody and prosody.paths and prosody.paths.data) or ".";
78 local callbacks = {};
79
80 ------- API -------------
81
82 function set_data_path(path)
83         log("debug", "Setting data path to: %s", path);
84         data_path = path;
85 end
86
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
91         end
92
93         return username, host, datastore, data;
94 end
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;
99                 return true;
100         end
101 end
102 function remove_callback(func)
103         if callbacks[func] then
104                 for i, f in ipairs(callbacks) do
105                         if f == func then
106                                 callbacks[i] = nil;
107                                 callbacks[f] = nil;
108                                 return true;
109                         end
110                 end
111         end
112 end
113
114 function getpath(username, host, datastore, ext, create)
115         ext = ext or "dat";
116         host = (host and encode(host)) or "_global";
117         username = username and encode(username);
118         if username then
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);
121         elseif host then
122                 if create then mkdir(mkdir(data_path).."/"..host); end
123                 return format("%s/%s/%s.%s", data_path, host, datastore, ext);
124         else
125                 if create then mkdir(data_path); end
126                 return format("%s/%s.%s", data_path, datastore, ext);
127         end
128 end
129
130 function load(username, host, datastore)
131         local data, ret = envloadfile(getpath(username, host, datastore), {});
132         if not data then
133                 local mode = lfs.attributes(getpath(username, host, datastore), "mode");
134                 if not mode then
135                         log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
136                         return 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";
141                 end
142         end
143
144         local success, ret = pcall(data);
145         if not success then
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";
148         end
149         return ret;
150 end
151
152 local function atomic_store(filename, data)
153         local scratch = filename.."~";
154         local f, ok, msg;
155         repeat
156                 f, msg = io_open(scratch, "w");
157                 if not f then break end
158
159                 ok, msg = f:write(data);
160                 if not ok then break end
161
162                 ok, msg = f:close();
163                 if not ok then break end
164
165                 return os_rename(scratch, filename);
166         until false;
167
168         -- Cleanup
169         if f then f:close(); end
170         os_remove(scratch);
171         return nil, msg;
172 end
173
174 function store(username, host, datastore, data)
175         if not data then
176                 data = {};
177         end
178
179         username, host, datastore, data = callback(username, host, datastore, data);
180         if username == false then
181                 return true; -- Don't save this data at all
182         end
183
184         -- save the datastore
185         local d = "return " .. serialize(data) .. ";\n";
186         local ok, msg = atomic_store(getpath(username, host, datastore, nil, true), d);
187         if not ok then
188                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
189                 return nil, "Error saving to storage";
190         end
191         if next(data) == nil then -- try to delete empty datastore
192                 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
193                 os_remove(getpath(username, host, datastore));
194         end
195         -- we write data even when we are deleting because lua doesn't have a
196         -- platform independent way of checking for non-exisitng files
197         return true;
198 end
199
200 function list_append(username, host, datastore, data)
201         if not data then return; end
202         if callback(username, host, datastore) == false then return true; end
203         -- save the datastore
204         local f, msg = io_open(getpath(username, host, datastore, "list", true), "r+");
205         if not f then
206                 f, msg = io_open(getpath(username, host, datastore, "list", true), "w");
207         end
208         if not f then
209                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
210                 return;
211         end
212         local data = "item(" ..  serialize(data) .. ");\n";
213         local pos = f:seek("end");
214         local ok, msg = fallocate(f, pos, #data);
215         f:seek("set", pos);
216         if ok then
217                 f:write(data);
218         else
219                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
220                 return ok, msg;
221         end
222         f:close();
223         return true;
224 end
225
226 function list_store(username, host, datastore, data)
227         if not data then
228                 data = {};
229         end
230         if callback(username, host, datastore) == false then return true; end
231         -- save the datastore
232         local d = {};
233         for _, item in ipairs(data) do
234                 d[#d+1] = "item(" .. serialize(item) .. ");\n";
235         end
236         local ok, msg = atomic_store(getpath(username, host, datastore, "list", true), t_concat(d));
237         if not ok then
238                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
239                 return;
240         end
241         if next(data) == nil then -- try to delete empty datastore
242                 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
243                 os_remove(getpath(username, host, datastore, "list"));
244         end
245         -- we write data even when we are deleting because lua doesn't have a
246         -- platform independent way of checking for non-exisitng files
247         return true;
248 end
249
250 function list_load(username, host, datastore)
251         local items = {};
252         local data, ret = envloadfile(getpath(username, host, datastore, "list"), {item = function(i) t_insert(items, i); end});
253         if not data then
254                 local mode = lfs.attributes(getpath(username, host, datastore, "list"), "mode");
255                 if not mode then
256                         log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
257                         return nil;
258                 else -- file exists, but can't be read
259                         -- TODO more detailed error checking and logging?
260                         log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
261                         return nil, "Error reading storage";
262                 end
263         end
264
265         local success, ret = pcall(data);
266         if not success then
267                 log("error", "Unable 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         return items;
271 end
272
273 function list_stores(username, host)
274         if not host then
275                 return nil, "bad argument #2 to 'list_stores' (string expected, got nothing)";
276         end
277         local list = {};
278         local host_dir = format("%s/%s/", data_path, encode(host));
279         for node in lfs.dir(host_dir) do
280                 if not node:match"^%." then -- dots should be encoded, this is probably . or ..
281                         local store = decode(node);
282                         local path = host_dir..node;
283                         if username == true then
284                                 if lfs.attributes(path, "mode") == "directory" then
285                                         list[#list+1] = store;
286                                 end
287                         elseif username then
288                                 if lfs.attributes(getpath(username, host, store), "mode")
289                                         or lfs.attributes(getpath(username, host, store, "list"), "mode") then
290                                         list[#list+1] = store;
291                                 end
292                         elseif lfs.attributes(path, "mode") == "file" then
293                                 list[#list+1] = store:gsub("%.[dalist]+$","");
294                         end
295                 end
296         end
297         return list;
298 end
299
300 function purge(username, host)
301         local host_dir = format("%s/%s/", data_path, encode(host));
302         local deleted = 0;
303         for file in lfs.dir(host_dir) do
304                 if lfs.attributes(host_dir..file, "mode") == "directory" then
305                         local store = decode(file);
306                         deleted = deleted + (os_remove(getpath(username, host, store)) and 1 or 0);
307                         deleted = deleted + (os_remove(getpath(username, host, store, "list")) and 1 or 0);
308                         -- We this will generate loads of "No such file or directory", but do we care?
309                 end
310         end
311         return deleted > 0, deleted;
312 end
313
314 return _M;