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 -- Will be modified by configure script if run --
12 CFG_SOURCEDIR=os.getenv("PROSODY_SRCDIR");
13 CFG_CONFIGDIR=os.getenv("PROSODY_CFGDIR");
14 CFG_PLUGINDIR=os.getenv("PROSODY_PLUGINDIR");
15 CFG_DATADIR=os.getenv("PROSODY_DATADIR");
17 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
19 -- Tell Lua where to find our libraries
21 package.path = CFG_SOURCEDIR.."/?.lua;"..package.path;
22 package.cpath = CFG_SOURCEDIR.."/?.so;"..package.cpath;
25 -- Substitute ~ with path to home directory in data path
27 if os.getenv("HOME") then
28 CFG_DATADIR = CFG_DATADIR:gsub("^~", os.getenv("HOME"));
32 -- Global 'prosody' object
33 prosody = { events = require "util.events".new(); };
34 local prosody = prosody;
36 -- Load the config-parsing module
37 config = require "core.configmanager"
40 -- Define the functions we call during startup, the
41 -- actual startup happens right at the end, where these
42 -- functions get called
44 function read_config()
48 if arg[1] == "--config" and arg[2] then
49 table.insert(filenames, arg[2]);
51 table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
54 for _, format in ipairs(config.parsers()) do
55 table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
58 for _,_filename in ipairs(filenames) do
60 local file = io.open(filename);
63 CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
67 local ok, level, err = config.load(filename);
70 print("**************************");
71 if level == "parser" then
72 print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
73 local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
74 print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
76 elseif level == "file" then
77 print("Prosody was unable to find the configuration file.");
78 print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
79 print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
80 print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
82 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
84 print("**************************");
90 function load_libraries()
91 -- Load socket framework
92 server = require "net.server"
95 function init_logging()
97 require "core.loggingmanager"
100 function check_dependencies()
101 -- Check runtime dependencies
102 if not require "util.dependencies".check_dependencies() then
107 function sandbox_require()
108 -- Replace require() with one that doesn't pollute _G, required
109 -- for neat sandboxing of modules
111 local _real_require = require;
112 function require(...)
113 local curr_env = getfenv(2);
114 local curr_env_mt = getmetatable(getfenv(2));
115 local _realG_mt = getmetatable(_realG);
116 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
118 old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
119 local ret = _real_require(...);
120 _realG_mt.__newindex = old_newindex;
123 return _real_require(...);
127 function set_function_metatable()
129 function mt.__index(f, upvalue)
130 local i, name, value = 0;
133 name, value = debug.getupvalue(f, i);
134 until name == upvalue or name == nil;
137 function mt.__newindex(f, upvalue, value)
141 name = debug.getupvalue(f, i);
142 until name == upvalue or name == nil;
144 debug.setupvalue(f, i, value);
147 debug.setmetatable(function() end, mt);
150 function init_global_state()
155 prosody.bare_sessions = bare_sessions;
156 prosody.full_sessions = full_sessions;
157 prosody.hosts = hosts;
159 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR,
160 plugins = CFG_PLUGINDIR, data = CFG_DATADIR };
162 prosody.arg = _G.arg;
164 prosody.platform = "unknown";
165 if os.getenv("WINDIR") then
166 prosody.platform = "windows";
167 elseif package.config:sub(1,1) == "/" then
168 prosody.platform = "posix";
171 prosody.installed = nil;
172 if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
173 prosody.installed = true;
176 -- Function to reload the config file
177 function prosody.reload_config()
178 log("info", "Reloading configuration file");
179 prosody.events.fire_event("reloading-config");
180 local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
182 if level == "parser" then
183 log("error", "There was an error parsing the configuration file: %s", tostring(err));
184 elseif level == "file" then
185 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
188 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
191 -- Function to reopen logfiles
192 function prosody.reopen_logfiles()
193 log("info", "Re-opening log files");
194 prosody.events.fire_event("reopen-log-files");
197 -- Function to initiate prosody shutdown
198 function prosody.shutdown(reason)
199 log("info", "Shutting down: %s", reason or "unknown reason");
200 prosody.shutdown_reason = reason;
201 prosody.events.fire_event("server-stopping", {reason = reason});
202 server.setquitting(true);
205 -- Load SSL settings from config, and create a ctx table
206 local certmanager = require "core.certmanager";
207 local global_ssl_ctx = certmanager.create_context("*", "server");
208 prosody.global_ssl_ctx = global_ssl_ctx;
210 local cl = require "net.connlisteners";
211 function prosody.net_activate_ports(option, listener, default, conntype)
212 conntype = conntype or (global_ssl_ctx and "tls") or "tcp";
213 local ports_option = option and option.."_ports" or "ports";
214 if not cl.get(listener) then return; end
215 local ports = config.get("*", "core", ports_option) or default;
216 if type(ports) == "number" then ports = {ports} end;
218 if type(ports) ~= "table" then
219 log("error", "core."..ports_option.." is not a table");
221 for _, port in ipairs(ports) do
222 port = tonumber(port);
223 if type(port) ~= "number" then
224 log("error", "Non-numeric "..ports_option..": "..tostring(port));
226 local ok, err = cl.start(listener, {
227 ssl = conntype == "ssl" and global_ssl_ctx,
229 interface = (option and config.get("*", "core", option.."_interface"))
230 or cl.get(listener).default_interface
231 or config.get("*", "core", "interface"),
235 local friendly_message = err;
236 if err:match(" in use") then
237 if port == 5222 or port == 5223 or port == 5269 then
238 friendly_message = "check that Prosody or another XMPP server is "
239 .."not already running and using this port";
240 elseif port == 80 or port == 81 then
241 friendly_message = "check that a HTTP server is not already using "
243 elseif port == 5280 then
244 friendly_message = "check that Prosody or a BOSH connection manager "
245 .."is not already running";
247 friendly_message = "this port is in use by another application";
249 elseif err:match("permission") then
250 friendly_message = "Prosody does not have sufficient privileges to use this port";
251 elseif err == "no ssl context" then
252 if not config.get("*", "core", "ssl") then
253 friendly_message = "there is no 'ssl' config under Host \"*\" which is "
254 .."require for legacy SSL ports";
256 friendly_message = "initializing SSL support failed, see previous log entries";
259 log("error", "Failed to open server port %d, %s", port, friendly_message);
267 function read_version()
268 -- Try to determine version
269 local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
271 prosody.version = version_file:read("*a"):gsub("%s*$", "");
272 version_file:close();
273 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
274 prosody.version = "hg:"..prosody.version;
277 prosody.version = "unknown";
281 function load_secondary_libraries()
282 --- Load and initialise core modules
283 require "util.import"
284 require "core.xmlhandlers"
285 require "core.rostermanager"
286 require "core.hostmanager"
287 require "core.modulemanager"
288 require "core.usermanager"
289 require "core.sessionmanager"
290 require "core.stanza_router"
295 require "util.datetime"
296 require "util.iterators"
298 require "util.helpers"
300 pcall(require, "util.signal") -- Not on Windows
302 -- Commented to protect us from
303 -- the second kind of people
305 pcall(require, "remdebug.engine");
306 if remdebug then remdebug.engine.start() end
309 require "net.connlisteners";
311 require "util.stanza"
315 function init_data_store()
316 local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
317 require "util.datamanager".set_data_path(data_path);
318 require "util.datamanager".add_callback(function(username, host, datastore, data)
319 if config.get(host, "core", "anonymous_login") then
322 return username, host, datastore, data;
326 function prepare_to_start()
327 log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
328 -- Signal to modules that we are ready to start
329 prosody.events.fire_event("server-starting");
331 -- start listening on sockets
332 if config.get("*", "core", "ports") then
333 prosody.net_activate_ports(nil, "multiplex", {5222, 5269});
334 if config.get("*", "core", "ssl_ports") then
335 prosody.net_activate_ports("ssl", "multiplex", {5223}, "ssl");
338 prosody.net_activate_ports("c2s", "xmppclient", {5222});
339 prosody.net_activate_ports("s2s", "xmppserver", {5269});
340 prosody.net_activate_ports("component", "xmppcomponent", {5347}, "tcp");
341 prosody.net_activate_ports("legacy_ssl", "xmppclient", {}, "ssl");
344 prosody.start_time = os.time();
347 function init_global_protection()
348 -- Catch global accesses
349 local locked_globals_mt = {
350 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
351 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
354 function prosody.unlock_globals()
355 setmetatable(_G, nil);
358 function prosody.lock_globals()
359 setmetatable(_G, locked_globals_mt);
363 prosody.lock_globals();
367 -- Error handler for errors that make it this far
368 local function catch_uncaught_error(err)
369 if type(err) == "string" and err:match("interrupted!$") then
373 log("error", "Top-level error, please report:\n%s", tostring(err));
374 local traceback = debug.traceback("", 2);
376 log("error", "%s", traceback);
379 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
382 while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
388 log("info", "Shutdown status: Cleaning up");
389 prosody.events.fire_event("server-cleanup");
391 -- Ok, we're quitting I know, but we
392 -- need to do some tidying before we go :)
393 server.setquitting(false);
395 log("info", "Shutdown status: Closing all active sessions");
396 for hostname, host in pairs(hosts) do
397 log("debug", "Shutdown status: Closing client connections for %s", hostname)
398 if host.sessions then
399 local reason = { condition = "system-shutdown", text = "Server is shutting down" };
400 if prosody.shutdown_reason then
401 reason.text = reason.text..": "..prosody.shutdown_reason;
403 for username, user in pairs(host.sessions) do
404 for resource, session in pairs(user.sessions) do
405 log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
406 session:close(reason);
411 log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
413 for remotehost, session in pairs(host.s2sout) do
414 if session.close then
415 session:close("system-shutdown");
417 log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
423 log("info", "Shutdown status: Closing all server connections");
426 server.setquitting(true);
430 -- These actions are in a strict order, as many depend on
431 -- previous steps to have already been performed
434 check_dependencies();
436 set_function_metatable();
440 log("info", "Hello and welcome to Prosody version %s", prosody.version);
441 load_secondary_libraries();
443 init_global_protection();
446 prosody.events.fire_event("server-started");
450 log("info", "Shutting down...");
452 prosody.events.fire_event("server-stopped");
453 log("info", "Shutdown complete");