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 if #arg > 0 and arg[1] ~= "--config" then
47 print("Unknown command-line option: "..tostring(arg[1]));
48 print("Perhaps you meant to use prosodyctl instead?");
52 -- Global 'prosody' object
53 local prosody = { events = require "util.events".new(); };
57 local dependencies = require "util.dependencies";
59 -- Load the config-parsing module
60 config = require "core.configmanager"
63 -- Define the functions we call during startup, the
64 -- actual startup happens right at the end, where these
65 -- functions get called
67 function read_config()
71 if arg[1] == "--config" and arg[2] then
72 table.insert(filenames, arg[2]);
74 table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
76 elseif os.getenv("PROSODY_CONFIG") then -- Passed by prosodyctl
77 table.insert(filenames, os.getenv("PROSODY_CONFIG"));
79 for _, format in ipairs(config.parsers()) do
80 table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
83 for _,_filename in ipairs(filenames) do
85 local file = io.open(filename);
88 CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
92 prosody.config_file = filename
93 local ok, level, err = config.load(filename);
96 print("**************************");
97 if level == "parser" then
98 print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua"..":");
100 local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
101 if err:match("chunk has too many syntax levels$") then
102 print("An Include statement in a config file is including an already-included");
103 print("file and causing an infinite loop. An Include statement in a config file is...");
105 print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
108 elseif level == "file" then
109 print("Prosody was unable to find the configuration file.");
110 print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
111 print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
112 print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
114 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
116 print("**************************");
122 function check_dependencies()
123 if not dependencies.check_dependencies() then
128 function load_libraries()
129 -- Load socket framework
130 socket = require "socket";
131 server = require "net.server"
134 function init_logging()
135 -- Initialize logging
136 require "core.loggingmanager"
139 function log_dependency_warnings()
140 dependencies.log_warnings();
143 function sanity_check()
144 for host, host_config in pairs(config.getconfig()) do
146 and host_config.enabled ~= false
147 and not host_config.component_module then
151 log("error", "No enabled VirtualHost entries found in the config file.");
152 log("error", "At least one active host is required for Prosody to function. Exiting...");
156 function sandbox_require()
157 -- Replace require() with one that doesn't pollute _G, required
158 -- for neat sandboxing of modules
160 local _real_require = require;
161 local getfenv = getfenv or function (f)
162 -- FIXME: This is a hack to replace getfenv() in Lua 5.2
163 local name, env = debug.getupvalue(debug.getinfo(f or 1).func, 1);
164 if name == "_ENV" then
168 function require(...)
169 local curr_env = getfenv(2);
170 local curr_env_mt = getmetatable(curr_env);
171 local _realG_mt = getmetatable(_realG);
172 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
173 local old_newindex, old_index;
174 old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
175 old_index, _realG_mt.__index = _realG_mt.__index, function (_G, k)
176 return rawget(curr_env, k);
178 local ret = _real_require(...);
179 _realG_mt.__newindex = old_newindex;
180 _realG_mt.__index = old_index;
183 return _real_require(...);
187 function set_function_metatable()
189 function mt.__index(f, upvalue)
190 local i, name, value = 0;
193 name, value = debug.getupvalue(f, i);
194 until name == upvalue or name == nil;
197 function mt.__newindex(f, upvalue, value)
201 name = debug.getupvalue(f, i);
202 until name == upvalue or name == nil;
204 debug.setupvalue(f, i, value);
207 function mt.__tostring(f)
208 local info = debug.getinfo(f);
209 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
211 debug.setmetatable(function() end, mt);
214 function init_global_state()
215 -- COMPAT: These globals are deprecated
220 prosody.bare_sessions = bare_sessions;
221 prosody.full_sessions = full_sessions;
222 prosody.hosts = hosts;
224 local data_path = config.get("*", "data_path") or CFG_DATADIR or "data";
225 local custom_plugin_paths = config.get("*", "plugin_paths");
226 if custom_plugin_paths then
227 local path_sep = package.config:sub(3,3);
228 -- path1;path2;path3;defaultpath...
229 CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
231 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR or ".",
232 plugins = CFG_PLUGINDIR or "plugins", data = data_path };
234 prosody.arg = _G.arg;
236 prosody.platform = "unknown";
237 if os.getenv("WINDIR") then
238 prosody.platform = "windows";
239 elseif package.config:sub(1,1) == "/" then
240 prosody.platform = "posix";
243 prosody.installed = nil;
244 if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
245 prosody.installed = true;
248 if prosody.installed then
249 -- Change working directory to data path.
250 require "lfs".chdir(data_path);
253 -- Function to reload the config file
254 function prosody.reload_config()
255 log("info", "Reloading configuration file");
256 prosody.events.fire_event("reloading-config");
257 local ok, level, err = config.load(prosody.config_file);
259 if level == "parser" then
260 log("error", "There was an error parsing the configuration file: %s", tostring(err));
261 elseif level == "file" then
262 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
265 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
268 -- Function to reopen logfiles
269 function prosody.reopen_logfiles()
270 log("info", "Re-opening log files");
271 prosody.events.fire_event("reopen-log-files");
274 -- Function to initiate prosody shutdown
275 function prosody.shutdown(reason, code)
276 log("info", "Shutting down: %s", reason or "unknown reason");
277 prosody.shutdown_reason = reason;
278 prosody.shutdown_code = code;
279 prosody.events.fire_event("server-stopping", {
283 server.setquitting(true);
287 function read_version()
288 -- Try to determine version
289 local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
291 prosody.version = version_file:read("*a"):gsub("%s*$", "");
292 version_file:close();
293 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
294 prosody.version = "hg:"..prosody.version;
297 prosody.version = "unknown";
301 function load_secondary_libraries()
302 --- Load and initialise core modules
303 require "util.import"
304 require "util.xmppstream"
305 require "core.stanza_router"
306 require "core.statsmanager"
307 require "core.hostmanager"
308 require "core.portmanager"
309 require "core.modulemanager"
310 require "core.usermanager"
311 require "core.rostermanager"
312 require "core.sessionmanager"
313 package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
314 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[ \t]*([^\n]*)"));
315 return function() end
321 require "util.datetime"
322 require "util.iterators"
324 require "util.helpers"
326 pcall(require, "util.signal") -- Not on Windows
328 -- Commented to protect us from
329 -- the second kind of people
331 pcall(require, "remdebug.engine");
332 if remdebug then remdebug.engine.start() end
335 require "util.stanza"
339 function init_data_store()
340 require "core.storagemanager";
343 function prepare_to_start()
344 log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
345 -- Signal to modules that we are ready to start
346 prosody.events.fire_event("server-starting");
347 prosody.start_time = os.time();
350 function init_global_protection()
351 -- Catch global accesses
352 local locked_globals_mt = {
353 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
354 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
357 function prosody.unlock_globals()
358 setmetatable(_G, nil);
361 function prosody.lock_globals()
362 setmetatable(_G, locked_globals_mt);
366 prosody.lock_globals();
370 -- Error handler for errors that make it this far
371 local function catch_uncaught_error(err)
372 if type(err) == "string" and err:match("interrupted!$") then
376 log("error", "Top-level error, please report:\n%s", tostring(err));
377 local traceback = debug.traceback("", 2);
379 log("error", "%s", traceback);
382 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
385 local sleep = require"socket".sleep;
387 while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
393 log("info", "Shutdown status: Cleaning up");
394 prosody.events.fire_event("server-cleanup");
398 -- These actions are in a strict order, as many depend on
399 -- previous steps to have already been performed
404 set_function_metatable();
405 check_dependencies();
409 log("info", "Hello and welcome to Prosody version %s", prosody.version);
410 log_dependency_warnings();
411 load_secondary_libraries();
413 init_global_protection();
416 prosody.events.fire_event("server-started");
420 log("info", "Shutting down...");
422 prosody.events.fire_event("server-stopped");
423 log("info", "Shutdown complete");
425 os.exit(prosody.shutdown_code)