Merge with Zash
[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, type = setmetatable, type;
12 local pairs, ipairs = pairs, 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 tostring, tonumber = tostring, tonumber;
19 local error = error;
20 local next = next;
21 local t_insert = table.insert;
22 local append = require "util.serialization".append;
23 local envloadfile = require"util.envload".envloadfile;
24 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)
25 local lfs = require "lfs";
26 local prosody = prosody;
27 local raw_mkdir;
28
29 if prosody.platform == "posix" then
30         raw_mkdir = require "util.pposix".mkdir; -- Doesn't trample on umask
31 else
32         raw_mkdir = lfs.mkdir;
33 end
34
35 module "datamanager"
36
37 ---- utils -----
38 local encode, decode;
39 do
40         local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
41
42         decode = function (s)
43                 return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
44         end
45
46         encode = function (s)
47                 return s and (s:gsub("%W", function (c) return format("%%%02x", c:byte()); end));
48         end
49 end
50
51 local _mkdir = {};
52 local function mkdir(path)
53         path = path:gsub("/", path_separator); -- TODO as an optimization, do this during path creation rather than here
54         if not _mkdir[path] then
55                 raw_mkdir(path);
56                 _mkdir[path] = true;
57         end
58         return path;
59 end
60
61 local data_path = (prosody and prosody.paths and prosody.paths.data) or ".";
62 local callbacks = {};
63
64 ------- API -------------
65
66 function set_data_path(path)
67         log("debug", "Setting data path to: %s", path);
68         data_path = path;
69 end
70
71 local function callback(username, host, datastore, data)
72         for _, f in ipairs(callbacks) do
73                 username, host, datastore, data = f(username, host, datastore, data);
74                 if username == false then break; end
75         end
76
77         return username, host, datastore, data;
78 end
79 function add_callback(func)
80         if not callbacks[func] then -- Would you really want to set the same callback more than once?
81                 callbacks[func] = true;
82                 callbacks[#callbacks+1] = func;
83                 return true;
84         end
85 end
86 function remove_callback(func)
87         if callbacks[func] then
88                 for i, f in ipairs(callbacks) do
89                         if f == func then
90                                 callbacks[i] = nil;
91                                 callbacks[f] = nil;
92                                 return true;
93                         end
94                 end
95         end
96 end
97
98 function getpath(username, host, datastore, ext, create)
99         ext = ext or "dat";
100         host = (host and encode(host)) or "_global";
101         username = username and encode(username);
102         if username then
103                 if create then mkdir(mkdir(mkdir(data_path).."/"..host).."/"..datastore); end
104                 return format("%s/%s/%s/%s.%s", data_path, host, datastore, username, ext);
105         elseif host then
106                 if create then mkdir(mkdir(data_path).."/"..host); end
107                 return format("%s/%s/%s.%s", data_path, host, datastore, ext);
108         else
109                 if create then mkdir(data_path); end
110                 return format("%s/%s.%s", data_path, datastore, ext);
111         end
112 end
113
114 function load(username, host, datastore)
115         local data, ret = envloadfile(getpath(username, host, datastore), {});
116         if not data then
117                 local mode = lfs.attributes(getpath(username, host, datastore), "mode");
118                 if not mode then
119                         log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
120                         return nil;
121                 else -- file exists, but can't be read
122                         -- TODO more detailed error checking and logging?
123                         log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
124                         return nil, "Error reading storage";
125                 end
126         end
127
128         local success, ret = pcall(data);
129         if not success then
130                 log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
131                 return nil, "Error reading storage";
132         end
133         return ret;
134 end
135
136 function store(username, host, datastore, data)
137         if not data then
138                 data = {};
139         end
140
141         username, host, datastore, data = callback(username, host, datastore, data);
142         if username == false then
143                 return true; -- Don't save this data at all
144         end
145
146         -- save the datastore
147         local f, msg = io_open(getpath(username, host, datastore, nil, true), "w+");
148         if not f then
149                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
150                 return nil, "Error saving to storage";
151         end
152         f:write("return ");
153         append(f, data);
154         f:close();
155         if next(data) == nil then -- try to delete empty datastore
156                 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
157                 os_remove(getpath(username, host, datastore));
158         end
159         -- we write data even when we are deleting because lua doesn't have a
160         -- platform independent way of checking for non-exisitng files
161         return true;
162 end
163
164 function list_append(username, host, datastore, data)
165         if not data then return; end
166         if callback(username, host, datastore) == false then return true; end
167         -- save the datastore
168         local f, msg = io_open(getpath(username, host, datastore, "list", true), "a+");
169         if not f then
170                 log("error", "Unable to write to %s storage ('%s') for user: %s@%s", datastore, msg, username or "nil", host or "nil");
171                 return;
172         end
173         f:write("item(");
174         append(f, data);
175         f:write(");\n");
176         f:close();
177         return true;
178 end
179
180 function list_store(username, host, datastore, data)
181         if not data then
182                 data = {};
183         end
184         if callback(username, host, datastore) == false then return true; end
185         -- save the datastore
186         local f, msg = io_open(getpath(username, host, datastore, "list", true), "w+");
187         if not f 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;
190         end
191         for _, d in ipairs(data) do
192                 f:write("item(");
193                 append(f, d);
194                 f:write(");\n");
195         end
196         f:close();
197         if next(data) == nil then -- try to delete empty datastore
198                 log("debug", "Removing empty %s datastore for user %s@%s", datastore, username or "nil", host or "nil");
199                 os_remove(getpath(username, host, datastore, "list"));
200         end
201         -- we write data even when we are deleting because lua doesn't have a
202         -- platform independent way of checking for non-exisitng files
203         return true;
204 end
205
206 function list_load(username, host, datastore)
207         local items = {};
208         local data, ret = envloadfile(getpath(username, host, datastore, "list"), {item = function(i) t_insert(items, i); end});
209         if not data then
210                 local mode = lfs.attributes(getpath(username, host, datastore, "list"), "mode");
211                 if not mode then
212                         log("debug", "Assuming empty %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
213                         return nil;
214                 else -- file exists, but can't be read
215                         -- TODO more detailed error checking and logging?
216                         log("error", "Failed to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
217                         return nil, "Error reading storage";
218                 end
219         end
220
221         local success, ret = pcall(data);
222         if not success then
223                 log("error", "Unable to load %s storage ('%s') for user: %s@%s", datastore, ret, username or "nil", host or "nil");
224                 return nil, "Error reading storage";
225         end
226         return items;
227 end
228
229 function list_stores(username, host)
230         if not host then
231                 return nil, "bad argument #2 to 'list_stores' (string expected, got nothing)";
232         end
233         local list = {};
234         local host_dir = format("%s/%s/", data_path, encode(host));
235         for node in lfs.dir(host_dir) do
236                 if not node:match"^%." then -- dots should be encoded, this is probably . or ..
237                         local store = decode(node);
238                         local path = host_dir..node;
239                         if username == true then
240                                 if lfs.attributes(path, "mode") == "directory" then
241                                         list[#list+1] = store;
242                                 end
243                         elseif username then
244                                 if lfs.attributes(getpath(username, host, store), "mode")
245                                         or lfs.attributes(getpath(username, host, store, "list"), "mode") then
246                                         list[#list+1] = store;
247                                 end
248                         elseif lfs.attributes(path, "mode") == "file" then
249                                 list[#list+1] = store:gsub("%.[dalist]+$","");
250                         end
251                 end
252         end
253         return list;
254 end
255
256 function purge(username, host)
257         local host_dir = format("%s/%s/", data_path, encode(host));
258         local deleted = 0;
259         for file in lfs.dir(host_dir) do
260                 if lfs.attributes(host_dir..file, "mode") == "directory" then
261                         local store = decode(file);
262                         deleted = deleted + (os_remove(getpath(username, host, store)) and 1 or 0);
263                         deleted = deleted + (os_remove(getpath(username, host, store, "list")) and 1 or 0);
264                         -- We this will generate loads of "No such file or directory", but do we care?
265                 end
266         end
267         return deleted > 0, deleted;
268 end
269
270 return _M;