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 sandbox_require()
131 -- Replace require() with one that doesn't pollute _G, required
132 -- for neat sandboxing of modules
134 local _real_require = require;
135 function require(...)
136 local curr_env = getfenv(2);
137 local curr_env_mt = getmetatable(getfenv(2));
138 local _realG_mt = getmetatable(_realG);
139 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
141 old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
142 local ret = _real_require(...);
143 _realG_mt.__newindex = old_newindex;
146 return _real_require(...);
150 function set_function_metatable()
152 function mt.__index(f, upvalue)
153 local i, name, value = 0;
156 name, value = debug.getupvalue(f, i);
157 until name == upvalue or name == nil;
160 function mt.__newindex(f, upvalue, value)
164 name = debug.getupvalue(f, i);
165 until name == upvalue or name == nil;
167 debug.setupvalue(f, i, value);
170 function mt.__tostring(f)
171 local info = debug.getinfo(f);
172 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
174 debug.setmetatable(function() end, mt);
177 function init_global_state()
182 prosody.bare_sessions = bare_sessions;
183 prosody.full_sessions = full_sessions;
184 prosody.hosts = hosts;
186 local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
187 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR,
188 plugins = CFG_PLUGINDIR, data = data_path };
190 prosody.arg = _G.arg;
192 prosody.platform = "unknown";
193 if os.getenv("WINDIR") then
194 prosody.platform = "windows";
195 elseif package.config:sub(1,1) == "/" then
196 prosody.platform = "posix";
199 prosody.installed = nil;
200 if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
201 prosody.installed = true;
204 -- Function to reload the config file
205 function prosody.reload_config()
206 log("info", "Reloading configuration file");
207 prosody.events.fire_event("reloading-config");
208 local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
210 if level == "parser" then
211 log("error", "There was an error parsing the configuration file: %s", tostring(err));
212 elseif level == "file" then
213 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
216 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
219 -- Function to reopen logfiles
220 function prosody.reopen_logfiles()
221 log("info", "Re-opening log files");
222 prosody.events.fire_event("reopen-log-files");
225 -- Function to initiate prosody shutdown
226 function prosody.shutdown(reason)
227 log("info", "Shutting down: %s", reason or "unknown reason");
228 prosody.shutdown_reason = reason;
229 prosody.events.fire_event("server-stopping", {reason = reason});
230 server.setquitting(true);
233 -- Load SSL settings from config, and create a ctx table
234 local certmanager = require "core.certmanager";
235 local global_ssl_ctx = certmanager.create_context("*", "server");
236 prosody.global_ssl_ctx = global_ssl_ctx;
238 local cl = require "net.connlisteners";
239 function prosody.net_activate_ports(option, listener, default, conntype)
240 conntype = conntype or (global_ssl_ctx and "tls") or "tcp";
241 local ports_option = option and option.."_ports" or "ports";
242 if not cl.get(listener) then return; end
243 local ports = config.get("*", "core", ports_option) or default;
244 if type(ports) == "number" then ports = {ports} end;
246 if type(ports) ~= "table" then
247 log("error", "core."..ports_option.." is not a table");
249 for _, port in ipairs(ports) do
250 port = tonumber(port);
251 if type(port) ~= "number" then
252 log("error", "Non-numeric "..ports_option..": "..tostring(port));
254 local ok, err = cl.start(listener, {
255 ssl = conntype == "ssl" and global_ssl_ctx,
257 interface = (option and config.get("*", "core", option.."_interface"))
258 or cl.get(listener).default_interface
259 or config.get("*", "core", "interface"),
263 local friendly_message = err;
264 if err:match(" in use") then
265 if port == 5222 or port == 5223 or port == 5269 then
266 friendly_message = "check that Prosody or another XMPP server is "
267 .."not already running and using this port";
268 elseif port == 80 or port == 81 then
269 friendly_message = "check that a HTTP server is not already using "
271 elseif port == 5280 then
272 friendly_message = "check that Prosody or a BOSH connection manager "
273 .."is not already running";
275 friendly_message = "this port is in use by another application";
277 elseif err:match("permission") then
278 friendly_message = "Prosody does not have sufficient privileges to use this port";
279 elseif err == "no ssl context" then
280 if not config.get("*", "core", "ssl") then
281 friendly_message = "there is no 'ssl' config under Host \"*\" which is "
282 .."require for legacy SSL ports";
284 friendly_message = "initializing SSL support failed, see previous log entries";
287 log("error", "Failed to open server port %d, %s", port, friendly_message);
295 function read_version()
296 -- Try to determine version
297 local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
299 prosody.version = version_file:read("*a"):gsub("%s*$", "");
300 version_file:close();
301 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
302 prosody.version = "hg:"..prosody.version;
305 prosody.version = "unknown";
309 function load_secondary_libraries()
310 --- Load and initialise core modules
311 require "util.import"
312 require "util.xmppstream"
313 require "core.rostermanager"
314 require "core.hostmanager"
315 require "core.modulemanager"
316 require "core.usermanager"
317 require "core.sessionmanager"
318 require "core.stanza_router"
319 package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
320 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[\s\t]*([^\n]*)"));
321 return function() end
327 require "util.datetime"
328 require "util.iterators"
330 require "util.helpers"
332 pcall(require, "util.signal") -- Not on Windows
334 -- Commented to protect us from
335 -- the second kind of people
337 pcall(require, "remdebug.engine");
338 if remdebug then remdebug.engine.start() end
341 require "net.connlisteners";
343 require "util.stanza"
347 function init_data_store()
348 require "core.storagemanager";
351 function prepare_to_start()
352 log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
353 -- Signal to modules that we are ready to start
354 prosody.events.fire_event("server-starting");
356 -- start listening on sockets
357 if config.get("*", "core", "ports") then
358 prosody.net_activate_ports(nil, "multiplex", {5222, 5269});
359 if config.get("*", "core", "ssl_ports") then
360 prosody.net_activate_ports("ssl", "multiplex", {5223}, "ssl");
363 prosody.net_activate_ports("c2s", "xmppclient", {5222});
364 prosody.net_activate_ports("s2s", "xmppserver", {5269});
365 prosody.net_activate_ports("component", "xmppcomponent", {5347}, "tcp");
366 prosody.net_activate_ports("legacy_ssl", "xmppclient", {}, "ssl");
369 prosody.start_time = os.time();
372 function init_global_protection()
373 -- Catch global accesses
374 local locked_globals_mt = {
375 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
376 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
379 function prosody.unlock_globals()
380 setmetatable(_G, nil);
383 function prosody.lock_globals()
384 setmetatable(_G, locked_globals_mt);
388 prosody.lock_globals();
392 -- Error handler for errors that make it this far
393 local function catch_uncaught_error(err)
394 if type(err) == "string" and err:match("interrupted!$") then
398 log("error", "Top-level error, please report:\n%s", tostring(err));
399 local traceback = debug.traceback("", 2);
401 log("error", "%s", traceback);
404 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
407 while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
413 log("info", "Shutdown status: Cleaning up");
414 prosody.events.fire_event("server-cleanup");
416 -- Ok, we're quitting I know, but we
417 -- need to do some tidying before we go :)
418 server.setquitting(false);
420 log("info", "Shutdown status: Closing all active sessions");
421 for hostname, host in pairs(hosts) do
422 log("debug", "Shutdown status: Closing client connections for %s", hostname)
423 if host.sessions then
424 local reason = { condition = "system-shutdown", text = "Server is shutting down" };
425 if prosody.shutdown_reason then
426 reason.text = reason.text..": "..prosody.shutdown_reason;
428 for username, user in pairs(host.sessions) do
429 for resource, session in pairs(user.sessions) do
430 log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
431 session:close(reason);
436 log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
438 for remotehost, session in pairs(host.s2sout) do
439 if session.close then
440 session:close("system-shutdown");
442 log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
448 log("info", "Shutdown status: Closing all server connections");
451 server.setquitting(true);
455 -- These actions are in a strict order, as many depend on
456 -- previous steps to have already been performed
460 set_function_metatable();
464 log("info", "Hello and welcome to Prosody version %s", prosody.version);
465 log_dependency_warnings();
466 load_secondary_libraries();
468 init_global_protection();
471 prosody.events.fire_event("server-started");
475 log("info", "Shutting down...");
477 prosody.events.fire_event("server-stopped");
478 log("info", "Shutdown complete");