3 -- Copyright (C) 2008-2010 Matthew Wild
4 -- Copyright (C) 2008-2010 Waqas Hussain
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
10 -- prosody - main executable for Prosody XMPP server
12 -- Will be modified by configure script if run --
14 CFG_SOURCEDIR=os.getenv("PROSODY_SRCDIR");
15 CFG_CONFIGDIR=os.getenv("PROSODY_CFGDIR");
16 CFG_PLUGINDIR=os.getenv("PROSODY_PLUGINDIR");
17 CFG_DATADIR=os.getenv("PROSODY_DATADIR");
19 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
21 local function is_relative(path)
22 local path_sep = package.config:sub(1,1);
23 return ((path_sep == "/" and path:sub(1,1) ~= "/")
24 or (path_sep == "\\" and (path:sub(1,1) ~= "/" and path:sub(2,3) ~= ":\\")))
27 -- Tell Lua where to find our libraries
29 local function filter_relative_paths(path)
30 if is_relative(path) then return ""; end
32 local function sanitise_paths(paths)
33 return (paths:gsub("[^;]+;?", filter_relative_paths):gsub(";;+", ";"));
35 package.path = sanitise_paths(CFG_SOURCEDIR.."/?.lua;"..package.path);
36 package.cpath = sanitise_paths(CFG_SOURCEDIR.."/?.so;"..package.cpath);
39 -- Substitute ~ with path to home directory in data path
41 if os.getenv("HOME") then
42 CFG_DATADIR = CFG_DATADIR:gsub("^~", os.getenv("HOME"));
46 -- Global 'prosody' object
47 local prosody = { events = require "util.events".new(); };
51 local dependencies = require "util.dependencies";
53 -- Load the config-parsing module
54 config = require "core.configmanager"
57 -- Define the functions we call during startup, the
58 -- actual startup happens right at the end, where these
59 -- functions get called
61 function read_config()
65 if arg[1] == "--config" and arg[2] then
66 table.insert(filenames, arg[2]);
68 table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
70 elseif os.getenv("PROSODY_CONFIG") then -- Passed by prosodyctl
71 table.insert(filenames, os.getenv("PROSODY_CONFIG"));
73 for _, format in ipairs(config.parsers()) do
74 table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
77 for _,_filename in ipairs(filenames) do
79 local file = io.open(filename);
82 CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
86 prosody.config_file = filename
87 local ok, level, err = config.load(filename);
90 print("**************************");
91 if level == "parser" then
92 print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua"..":");
94 local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
95 if err:match("chunk has too many syntax levels$") then
96 print("An Include statement in a config file is including an already-included");
97 print("file and causing an infinite loop. An Include statement in a config file is...");
99 print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
102 elseif level == "file" then
103 print("Prosody was unable to find the configuration file.");
104 print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
105 print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
106 print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
108 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
110 print("**************************");
116 function check_dependencies()
117 if not dependencies.check_dependencies() then
122 function load_libraries()
123 -- Load socket framework
124 server = require "net.server"
127 function init_logging()
128 -- Initialize logging
129 require "core.loggingmanager"
132 function log_dependency_warnings()
133 dependencies.log_warnings();
136 function sanity_check()
137 for host, host_config in pairs(config.getconfig()) do
139 and host_config.enabled ~= false
140 and not host_config.component_module then
144 log("error", "No enabled VirtualHost entries found in the config file.");
145 log("error", "At least one active host is required for Prosody to function. Exiting...");
149 function sandbox_require()
150 -- Replace require() with one that doesn't pollute _G, required
151 -- for neat sandboxing of modules
153 local _real_require = require;
154 local getfenv = getfenv or function (f)
155 -- FIXME: This is a hack to replace getfenv() in Lua 5.2
156 local name, env = debug.getupvalue(debug.getinfo(f or 1).func, 1);
157 if name == "_ENV" then
161 function require(...)
162 local curr_env = getfenv(2);
163 local curr_env_mt = getmetatable(curr_env);
164 local _realG_mt = getmetatable(_realG);
165 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
166 local old_newindex, old_index;
167 old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
168 old_index, _realG_mt.__index = _realG_mt.__index, function (_G, k)
169 return rawget(curr_env, k);
171 local ret = _real_require(...);
172 _realG_mt.__newindex = old_newindex;
173 _realG_mt.__index = old_index;
176 return _real_require(...);
180 function set_function_metatable()
182 function mt.__index(f, upvalue)
183 local i, name, value = 0;
186 name, value = debug.getupvalue(f, i);
187 until name == upvalue or name == nil;
190 function mt.__newindex(f, upvalue, value)
194 name = debug.getupvalue(f, i);
195 until name == upvalue or name == nil;
197 debug.setupvalue(f, i, value);
200 function mt.__tostring(f)
201 local info = debug.getinfo(f);
202 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
204 debug.setmetatable(function() end, mt);
207 function init_global_state()
208 -- COMPAT: These globals are deprecated
213 prosody.bare_sessions = bare_sessions;
214 prosody.full_sessions = full_sessions;
215 prosody.hosts = hosts;
217 local data_path = config.get("*", "data_path") or CFG_DATADIR or "data";
218 local custom_plugin_paths = config.get("*", "plugin_paths");
219 if custom_plugin_paths then
220 local path_sep = package.config:sub(3,3);
221 -- path1;path2;path3;defaultpath...
222 CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
224 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR or ".",
225 plugins = CFG_PLUGINDIR or "plugins", data = data_path };
227 prosody.arg = _G.arg;
229 prosody.platform = "unknown";
230 if os.getenv("WINDIR") then
231 prosody.platform = "windows";
232 elseif package.config:sub(1,1) == "/" then
233 prosody.platform = "posix";
236 prosody.installed = nil;
237 if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
238 prosody.installed = true;
241 if prosody.installed then
242 -- Change working directory to data path.
243 require "lfs".chdir(data_path);
246 -- Function to reload the config file
247 function prosody.reload_config()
248 log("info", "Reloading configuration file");
249 prosody.events.fire_event("reloading-config");
250 local ok, level, err = config.load(prosody.config_file);
252 if level == "parser" then
253 log("error", "There was an error parsing the configuration file: %s", tostring(err));
254 elseif level == "file" then
255 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
258 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
261 -- Function to reopen logfiles
262 function prosody.reopen_logfiles()
263 log("info", "Re-opening log files");
264 prosody.events.fire_event("reopen-log-files");
267 -- Function to initiate prosody shutdown
268 function prosody.shutdown(reason)
269 log("info", "Shutting down: %s", reason or "unknown reason");
270 prosody.shutdown_reason = reason;
271 prosody.events.fire_event("server-stopping", {reason = reason});
272 server.setquitting(true);
276 function read_version()
277 -- Try to determine version
278 local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
280 prosody.version = version_file:read("*a"):gsub("%s*$", "");
281 version_file:close();
282 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
283 prosody.version = "hg:"..prosody.version;
286 prosody.version = "unknown";
290 function load_secondary_libraries()
291 --- Load and initialise core modules
292 require "util.import"
293 require "util.xmppstream"
294 require "core.stanza_router"
295 require "core.statsmanager"
296 require "core.hostmanager"
297 require "core.portmanager"
298 require "core.modulemanager"
299 require "core.usermanager"
300 require "core.rostermanager"
301 require "core.sessionmanager"
302 package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
303 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[ \t]*([^\n]*)"));
304 return function() end
310 require "util.datetime"
311 require "util.iterators"
313 require "util.helpers"
315 pcall(require, "util.signal") -- Not on Windows
317 -- Commented to protect us from
318 -- the second kind of people
320 pcall(require, "remdebug.engine");
321 if remdebug then remdebug.engine.start() end
324 require "util.stanza"
328 function init_data_store()
329 require "core.storagemanager";
332 function prepare_to_start()
333 log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
334 -- Signal to modules that we are ready to start
335 prosody.events.fire_event("server-starting");
336 prosody.start_time = os.time();
339 function init_global_protection()
340 -- Catch global accesses
341 local locked_globals_mt = {
342 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
343 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
346 function prosody.unlock_globals()
347 setmetatable(_G, nil);
350 function prosody.lock_globals()
351 setmetatable(_G, locked_globals_mt);
355 prosody.lock_globals();
359 -- Error handler for errors that make it this far
360 local function catch_uncaught_error(err)
361 if type(err) == "string" and err:match("interrupted!$") then
365 log("error", "Top-level error, please report:\n%s", tostring(err));
366 local traceback = debug.traceback("", 2);
368 log("error", "%s", traceback);
371 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
374 while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
380 log("info", "Shutdown status: Cleaning up");
381 prosody.events.fire_event("server-cleanup");
385 -- These actions are in a strict order, as many depend on
386 -- previous steps to have already been performed
391 set_function_metatable();
392 check_dependencies();
396 log("info", "Hello and welcome to Prosody version %s", prosody.version);
397 log_dependency_warnings();
398 load_secondary_libraries();
400 init_global_protection();
403 prosody.events.fire_event("server-started");
407 log("info", "Shutting down...");
409 prosody.events.fire_event("server-stopped");
410 log("info", "Shutdown complete");