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";
52 if not dependencies.check_dependencies() then
56 -- Load the config-parsing module
57 config = require "core.configmanager"
60 -- Define the functions we call during startup, the
61 -- actual startup happens right at the end, where these
62 -- functions get called
64 function read_config()
68 if arg[1] == "--config" and arg[2] then
69 table.insert(filenames, arg[2]);
71 table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
74 for _, format in ipairs(config.parsers()) do
75 table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
78 for _,_filename in ipairs(filenames) do
80 local file = io.open(filename);
83 CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
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 load_libraries()
117 -- Load socket framework
118 server = require "net.server"
121 function init_logging()
122 -- Initialize logging
123 require "core.loggingmanager"
126 function log_dependency_warnings()
127 dependencies.log_warnings();
130 function sanity_check()
131 for host, host_config in pairs(config.getconfig()) do
133 and host_config.core.enabled ~= false
134 and not host_config.core.component_module then
138 log("error", "No enabled VirtualHost entries found in the config file.");
139 log("error", "At least one active host is required for Prosody to function. Exiting...");
143 function sandbox_require()
144 -- Replace require() with one that doesn't pollute _G, required
145 -- for neat sandboxing of modules
147 local _real_require = require;
149 -- FIXME: This is a hack to replace getfenv() in Lua 5.2
150 function getfenv(f) return debug.getupvalue(debug.getinfo(f or 1).func, 1); end
152 function require(...)
153 local curr_env = getfenv(2);
154 local curr_env_mt = getmetatable(curr_env);
155 local _realG_mt = getmetatable(_realG);
156 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
157 local old_newindex, old_index;
158 old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
159 old_index, _realG_mt.__index = _realG_mt.__index, function (_G, k)
160 return rawget(curr_env, k);
162 local ret = _real_require(...);
163 _realG_mt.__newindex = old_newindex;
164 _realG_mt.__index = old_index;
167 return _real_require(...);
171 function set_function_metatable()
173 function mt.__index(f, upvalue)
174 local i, name, value = 0;
177 name, value = debug.getupvalue(f, i);
178 until name == upvalue or name == nil;
181 function mt.__newindex(f, upvalue, value)
185 name = debug.getupvalue(f, i);
186 until name == upvalue or name == nil;
188 debug.setupvalue(f, i, value);
191 function mt.__tostring(f)
192 local info = debug.getinfo(f);
193 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
195 debug.setmetatable(function() end, mt);
198 function init_global_state()
203 prosody.bare_sessions = bare_sessions;
204 prosody.full_sessions = full_sessions;
205 prosody.hosts = hosts;
207 local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
208 local custom_plugin_paths = config.get("*", "core", "plugin_paths");
209 if custom_plugin_paths then
210 local path_sep = package.config:sub(3,3);
211 -- path1;path2;path3;defaultpath...
212 CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
214 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR or ".",
215 plugins = CFG_PLUGINDIR or "plugins", data = data_path };
217 prosody.arg = _G.arg;
219 prosody.platform = "unknown";
220 if os.getenv("WINDIR") then
221 prosody.platform = "windows";
222 elseif package.config:sub(1,1) == "/" then
223 prosody.platform = "posix";
226 prosody.installed = nil;
227 if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
228 prosody.installed = true;
231 if prosody.installed then
232 -- Change working directory to data path.
233 require "lfs".chdir(data_path);
236 -- Function to reload the config file
237 function prosody.reload_config()
238 log("info", "Reloading configuration file");
239 prosody.events.fire_event("reloading-config");
240 local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
242 if level == "parser" then
243 log("error", "There was an error parsing the configuration file: %s", tostring(err));
244 elseif level == "file" then
245 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
248 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
251 -- Function to reopen logfiles
252 function prosody.reopen_logfiles()
253 log("info", "Re-opening log files");
254 prosody.events.fire_event("reopen-log-files");
257 -- Function to initiate prosody shutdown
258 function prosody.shutdown(reason)
259 log("info", "Shutting down: %s", reason or "unknown reason");
260 prosody.shutdown_reason = reason;
261 prosody.events.fire_event("server-stopping", {reason = reason});
262 server.setquitting(true);
265 -- Load SSL settings from config, and create a ctx table
266 local certmanager = require "core.certmanager";
267 local global_ssl_ctx = certmanager.create_context("*", "server");
268 prosody.global_ssl_ctx = global_ssl_ctx;
272 function read_version()
273 -- Try to determine version
274 local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
276 prosody.version = version_file:read("*a"):gsub("%s*$", "");
277 version_file:close();
278 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
279 prosody.version = "hg:"..prosody.version;
282 prosody.version = "unknown";
286 function load_secondary_libraries()
287 --- Load and initialise core modules
288 require "util.import"
289 require "util.xmppstream"
290 require "core.rostermanager"
291 require "core.stanza_router"
292 require "core.hostmanager"
293 require "core.portmanager"
294 require "core.modulemanager"
295 require "core.usermanager"
296 require "core.sessionmanager"
297 package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
298 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[ \t]*([^\n]*)"));
299 return function() end
305 require "util.datetime"
306 require "util.iterators"
308 require "util.helpers"
310 pcall(require, "util.signal") -- Not on Windows
312 -- Commented to protect us from
313 -- the second kind of people
315 pcall(require, "remdebug.engine");
316 if remdebug then remdebug.engine.start() end
319 require "util.stanza"
323 function init_data_store()
324 require "core.storagemanager";
327 function prepare_to_start()
328 log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
329 -- Signal to modules that we are ready to start
330 prosody.events.fire_event("server-starting");
331 prosody.start_time = os.time();
334 function init_global_protection()
335 -- Catch global accesses
336 local locked_globals_mt = {
337 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
338 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
341 function prosody.unlock_globals()
342 setmetatable(_G, nil);
345 function prosody.lock_globals()
346 setmetatable(_G, locked_globals_mt);
350 prosody.lock_globals();
354 -- Error handler for errors that make it this far
355 local function catch_uncaught_error(err)
356 if type(err) == "string" and err:match("interrupted!$") then
360 log("error", "Top-level error, please report:\n%s", tostring(err));
361 local traceback = debug.traceback("", 2);
363 log("error", "%s", traceback);
366 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
369 while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
375 log("info", "Shutdown status: Cleaning up");
376 prosody.events.fire_event("server-cleanup");
378 -- Ok, we're quitting I know, but we
379 -- need to do some tidying before we go :)
380 server.setquitting(false);
382 log("info", "Shutdown status: Closing all active sessions");
383 for hostname, host in pairs(hosts) do
384 log("debug", "Shutdown status: Closing client connections for %s", hostname)
385 if host.sessions then
386 local reason = { condition = "system-shutdown", text = "Server is shutting down" };
387 if prosody.shutdown_reason then
388 reason.text = reason.text..": "..prosody.shutdown_reason;
390 for username, user in pairs(host.sessions) do
391 for resource, session in pairs(user.sessions) do
392 log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
393 session:close(reason);
398 log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
400 for remotehost, session in pairs(host.s2sout) do
401 if session.close then
402 session:close("system-shutdown");
404 log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
410 log("info", "Shutdown status: Closing all server connections");
413 server.setquitting(true);
417 -- These actions are in a strict order, as many depend on
418 -- previous steps to have already been performed
423 set_function_metatable();
427 log("info", "Hello and welcome to Prosody version %s", prosody.version);
428 log_dependency_warnings();
429 load_secondary_libraries();
431 init_global_protection();
434 prosody.events.fire_event("server-started");
438 log("info", "Shutting down...");
440 prosody.events.fire_event("server-stopped");
441 log("info", "Shutdown complete");