configmanager: Added rawget().
[prosody.git] / core / configmanager.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 local _G = _G;
10 local setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type, pairs, table =
11       setmetatable, loadfile, pcall, rawget, rawset, io, error, dofile, type, pairs, table;
12 local format, math_max = string.format, math.max;
13
14 local fire_event = prosody and prosody.events.fire_event or function () end;
15
16 local lfs = require "lfs";
17 local path_sep = package.config:sub(1,1);
18
19 module "configmanager"
20
21 local parsers = {};
22
23 local config_mt = { __index = function (t, k) return rawget(t, "*"); end};
24 local config = setmetatable({ ["*"] = { core = {} } }, config_mt);
25
26 -- When host not found, use global
27 local host_mt = { };
28
29 -- When key not found in section, check key in global's section
30 function section_mt(section_name)
31         return { __index =      function (t, k)
32                                         local section = rawget(config["*"], section_name);
33                                         if not section then return nil; end
34                                         return section[k];
35                                 end
36         };
37 end
38
39 function getconfig()
40         return config;
41 end
42
43 function get(host, section, key)
44         local sec = config[host][section];
45         if sec then
46                 return sec[key];
47         end
48         return nil;
49 end
50 function _M.rawget(host, section, key)
51         local hostconfig = rawget(config, host);
52         if hostconfig then
53                 local sectionconfig = rawget(hostconfig, section);
54                 if sectionconfig then
55                         return rawget(sectionconfig, key);
56                 end
57         end
58 end
59
60 local function set(config, host, section, key, value)
61         if host and section and key then
62                 local hostconfig = rawget(config, host);
63                 if not hostconfig then
64                         hostconfig = rawset(config, host, setmetatable({}, host_mt))[host];
65                 end
66                 if not rawget(hostconfig, section) then
67                         hostconfig[section] = setmetatable({}, section_mt(section));
68                 end
69                 hostconfig[section][key] = value;
70                 return true;
71         end
72         return false;
73 end
74
75 function _M.set(host, section, key, value)
76         return set(config, host, section, key, value);
77 end
78
79 -- Helper function to resolve relative paths (needed by config)
80 do
81         local rel_path_start = ".."..path_sep;
82         function resolve_relative_path(parent_path, path)
83                 if path then
84                         -- Some normalization
85                         parent_path = parent_path:gsub("%"..path_sep.."+$", "");
86                         path = path:gsub("^%.%"..path_sep.."+", "");
87                         
88                         local is_relative;
89                         if path_sep == "/" and path:sub(1,1) ~= "/" then
90                                 is_relative = true;
91                         elseif path_sep == "\\" and (path:sub(1,1) ~= "/" and path:sub(2,3) ~= ":\\") then
92                                 is_relative = true;
93                         end
94                         if is_relative then
95                                 return parent_path..path_sep..path;
96                         end
97                 end
98                 return path;
99         end     
100 end
101
102 -- Helper function to convert a glob to a Lua pattern
103 local function glob_to_pattern(glob)
104         return "^"..glob:gsub("[%p*?]", function (c)
105                 if c == "*" then
106                         return ".*";
107                 elseif c == "?" then
108                         return ".";
109                 else
110                         return "%"..c;
111                 end
112         end).."$";
113 end
114
115 function load(filename, format)
116         format = format or filename:match("%w+$");
117
118         if parsers[format] and parsers[format].load then
119                 local f, err = io.open(filename);
120                 if f then
121                         local new_config = setmetatable({ ["*"] = { core = {} } }, config_mt);
122                         local ok, err = parsers[format].load(f:read("*a"), filename, new_config);
123                         f:close();
124                         if ok then
125                                 config = new_config;
126                                 fire_event("config-reloaded", {
127                                         filename = filename,
128                                         format = format,
129                                         config = config
130                                 });
131                         end
132                         return ok, "parser", err;
133                 end
134                 return f, "file", err;
135         end
136
137         if not format then
138                 return nil, "file", "no parser specified";
139         else
140                 return nil, "file", "no parser for "..(format);
141         end
142 end
143
144 function save(filename, format)
145 end
146
147 function addparser(format, parser)
148         if format and parser then
149                 parsers[format] = parser;
150         end
151 end
152
153 -- _M needed to avoid name clash with local 'parsers'
154 function _M.parsers()
155         local p = {};
156         for format in pairs(parsers) do
157                 table.insert(p, format);
158         end
159         return p;
160 end
161
162 -- Built-in Lua parser
163 do
164         local loadstring, pcall, setmetatable = _G.loadstring, _G.pcall, _G.setmetatable;
165         local setfenv, rawget, tostring = _G.setfenv, _G.rawget, _G.tostring;
166         parsers.lua = {};
167         function parsers.lua.load(data, config_file, config)
168                 local env;
169                 -- The ' = true' are needed so as not to set off __newindex when we assign the functions below
170                 env = setmetatable({
171                         Host = true, host = true, VirtualHost = true,
172                         Component = true, component = true,
173                         Include = true, include = true, RunScript = true }, {
174                                 __index = function (t, k)
175                                         return rawget(_G, k) or
176                                                 function (settings_table)
177                                                         config[__currenthost or "*"][k] = settings_table;
178                                                 end;
179                                 end,
180                                 __newindex = function (t, k, v)
181                                         set(config, env.__currenthost or "*", "core", k, v);
182                                 end
183                 });
184                 
185                 rawset(env, "__currenthost", "*") -- Default is global
186                 function env.VirtualHost(name)
187                         if rawget(config, name) and rawget(config[name].core, "component_module") then
188                                 error(format("Host %q clashes with previously defined %s Component %q, for services use a sub-domain like conference.%s",
189                                         name, config[name].core.component_module:gsub("^%a+$", { component = "external", muc = "MUC"}), name, name), 0);
190                         end
191                         rawset(env, "__currenthost", name);
192                         -- Needs at least one setting to logically exist :)
193                         set(config, name or "*", "core", "defined", true);
194                         return function (config_options)
195                                 rawset(env, "__currenthost", "*"); -- Return to global scope
196                                 for option_name, option_value in pairs(config_options) do
197                                         set(config, name or "*", "core", option_name, option_value);
198                                 end
199                         end;
200                 end
201                 env.Host, env.host = env.VirtualHost, env.VirtualHost;
202                 
203                 function env.Component(name)
204                         if rawget(config, name) and rawget(config[name].core, "defined") and not rawget(config[name].core, "component_module") then
205                                 error(format("Component %q clashes with previously defined Host %q, for services use a sub-domain like conference.%s",
206                                         name, name, name), 0);
207                         end
208                         set(config, name, "core", "component_module", "component");
209                         -- Don't load the global modules by default
210                         set(config, name, "core", "load_global_modules", false);
211                         rawset(env, "__currenthost", name);
212                         local function handle_config_options(config_options)
213                                 rawset(env, "__currenthost", "*"); -- Return to global scope
214                                 for option_name, option_value in pairs(config_options) do
215                                         set(config, name or "*", "core", option_name, option_value);
216                                 end
217                         end
218         
219                         return function (module)
220                                         if type(module) == "string" then
221                                                 set(config, name, "core", "component_module", module);
222                                                 return handle_config_options;
223                                         end
224                                         return handle_config_options(module);
225                                 end
226                 end
227                 env.component = env.Component;
228                 
229                 function env.Include(file, wildcard)
230                         if file:match("[*?]") then
231                                 local path_pos, glob = file:match("()([^"..path_sep.."]+)$");
232                                 local path = file:sub(1, math_max(path_pos-2,0));
233                                 local config_path = config_file:gsub("[^"..path_sep.."]+$", "");
234                                 if #path > 0 then
235                                         path = resolve_relative_path(config_path, path);
236                                 else
237                                         path = config_path;
238                                 end
239                                 local patt = glob_to_pattern(glob);
240                                 for f in lfs.dir(path) do
241                                         if f:sub(1,1) ~= "." and f:match(patt) then
242                                                 env.Include(path..path_sep..f);
243                                         end
244                                 end
245                         else
246                                 local f, err = io.open(file);
247                                 if f then
248                                         local data = f:read("*a");
249                                         local file = resolve_relative_path(config_file:gsub("[^"..path_sep.."]+$", ""), file);
250                                         local ret, err = parsers.lua.load(data, file, config);
251                                         if not ret then error(err:gsub("%[string.-%]", file), 0); end
252                                 end
253                                 if not f then error("Error loading included "..file..": "..err, 0); end
254                                 return f, err;
255                         end
256                 end
257                 env.include = env.Include;
258                 
259                 function env.RunScript(file)
260                         return dofile(resolve_relative_path(config_file:gsub("[^"..path_sep.."]+$", ""), file));
261                 end
262                 
263                 local chunk, err = loadstring(data, "@"..config_file);
264                 
265                 if not chunk then
266                         return nil, err;
267                 end
268                 
269                 setfenv(chunk, env);
270                 
271                 local ok, err = pcall(chunk);
272                 
273                 if not ok then
274                         return nil, err;
275                 end
276                 
277                 return true;
278         end
279         
280 end
281
282 return _M;