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 -- Tell Lua where to find our libraries
23 package.path = CFG_SOURCEDIR.."/?.lua;"..package.path;
24 package.cpath = CFG_SOURCEDIR.."/?.so;"..package.cpath;
27 -- Substitute ~ with path to home directory in data path
29 if os.getenv("HOME") then
30 CFG_DATADIR = CFG_DATADIR:gsub("^~", os.getenv("HOME"));
34 -- Global 'prosody' object
35 prosody = { events = require "util.events".new(); };
36 local prosody = prosody;
39 local dependencies = require "util.dependencies";
40 if not dependencies.check_dependencies() then
44 -- Load the config-parsing module
45 config = require "core.configmanager"
48 -- Define the functions we call during startup, the
49 -- actual startup happens right at the end, where these
50 -- functions get called
52 function read_config()
56 if arg[1] == "--config" and arg[2] then
57 table.insert(filenames, arg[2]);
59 table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
62 for _, format in ipairs(config.parsers()) do
63 table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
66 for _,_filename in ipairs(filenames) do
68 local file = io.open(filename);
71 CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
75 local ok, level, err = config.load(filename);
78 print("**************************");
79 if level == "parser" then
80 print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
81 local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
82 print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
84 elseif level == "file" then
85 print("Prosody was unable to find the configuration file.");
86 print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
87 print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
88 print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
90 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
92 print("**************************");
98 function load_libraries()
99 -- Load socket framework
100 server = require "net.server"
103 function init_logging()
104 -- Initialize logging
105 require "core.loggingmanager"
108 function log_dependency_warnings()
109 dependencies.log_warnings();
112 function sandbox_require()
113 -- Replace require() with one that doesn't pollute _G, required
114 -- for neat sandboxing of modules
116 local _real_require = require;
117 function require(...)
118 local curr_env = getfenv(2);
119 local curr_env_mt = getmetatable(getfenv(2));
120 local _realG_mt = getmetatable(_realG);
121 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
123 old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
124 local ret = _real_require(...);
125 _realG_mt.__newindex = old_newindex;
128 return _real_require(...);
132 function set_function_metatable()
134 function mt.__index(f, upvalue)
135 local i, name, value = 0;
138 name, value = debug.getupvalue(f, i);
139 until name == upvalue or name == nil;
142 function mt.__newindex(f, upvalue, value)
146 name = debug.getupvalue(f, i);
147 until name == upvalue or name == nil;
149 debug.setupvalue(f, i, value);
152 function mt.__tostring(f)
153 local info = debug.getinfo(f);
154 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
156 debug.setmetatable(function() end, mt);
159 function init_global_state()
164 prosody.bare_sessions = bare_sessions;
165 prosody.full_sessions = full_sessions;
166 prosody.hosts = hosts;
168 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR,
169 plugins = CFG_PLUGINDIR, data = CFG_DATADIR };
171 prosody.arg = _G.arg;
173 prosody.platform = "unknown";
174 if os.getenv("WINDIR") then
175 prosody.platform = "windows";
176 elseif package.config:sub(1,1) == "/" then
177 prosody.platform = "posix";
180 prosody.installed = nil;
181 if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
182 prosody.installed = true;
185 -- Function to reload the config file
186 function prosody.reload_config()
187 log("info", "Reloading configuration file");
188 prosody.events.fire_event("reloading-config");
189 local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
191 if level == "parser" then
192 log("error", "There was an error parsing the configuration file: %s", tostring(err));
193 elseif level == "file" then
194 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
197 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
200 -- Function to reopen logfiles
201 function prosody.reopen_logfiles()
202 log("info", "Re-opening log files");
203 prosody.events.fire_event("reopen-log-files");
206 -- Function to initiate prosody shutdown
207 function prosody.shutdown(reason)
208 log("info", "Shutting down: %s", reason or "unknown reason");
209 prosody.shutdown_reason = reason;
210 prosody.events.fire_event("server-stopping", {reason = reason});
211 server.setquitting(true);
214 -- Load SSL settings from config, and create a ctx table
215 local certmanager = require "core.certmanager";
216 local global_ssl_ctx = certmanager.create_context("*", "server");
217 prosody.global_ssl_ctx = global_ssl_ctx;
219 local cl = require "net.connlisteners";
220 function prosody.net_activate_ports(option, listener, default, conntype)
221 conntype = conntype or (global_ssl_ctx and "tls") or "tcp";
222 local ports_option = option and option.."_ports" or "ports";
223 if not cl.get(listener) then return; end
224 local ports = config.get("*", "core", ports_option) or default;
225 if type(ports) == "number" then ports = {ports} end;
227 if type(ports) ~= "table" then
228 log("error", "core."..ports_option.." is not a table");
230 for _, port in ipairs(ports) do
231 port = tonumber(port);
232 if type(port) ~= "number" then
233 log("error", "Non-numeric "..ports_option..": "..tostring(port));
235 local ok, err = cl.start(listener, {
236 ssl = conntype == "ssl" and global_ssl_ctx,
238 interface = (option and config.get("*", "core", option.."_interface"))
239 or cl.get(listener).default_interface
240 or config.get("*", "core", "interface"),
244 local friendly_message = err;
245 if err:match(" in use") then
246 if port == 5222 or port == 5223 or port == 5269 then
247 friendly_message = "check that Prosody or another XMPP server is "
248 .."not already running and using this port";
249 elseif port == 80 or port == 81 then
250 friendly_message = "check that a HTTP server is not already using "
252 elseif port == 5280 then
253 friendly_message = "check that Prosody or a BOSH connection manager "
254 .."is not already running";
256 friendly_message = "this port is in use by another application";
258 elseif err:match("permission") then
259 friendly_message = "Prosody does not have sufficient privileges to use this port";
260 elseif err == "no ssl context" then
261 if not config.get("*", "core", "ssl") then
262 friendly_message = "there is no 'ssl' config under Host \"*\" which is "
263 .."require for legacy SSL ports";
265 friendly_message = "initializing SSL support failed, see previous log entries";
268 log("error", "Failed to open server port %d, %s", port, friendly_message);
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.rostermanager"
295 require "core.hostmanager"
296 require "core.modulemanager"
297 require "core.usermanager"
298 require "core.sessionmanager"
299 require "core.stanza_router"
300 package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
301 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[\s\t]*([^\n]*)"));
302 return function() end
308 require "util.datetime"
309 require "util.iterators"
311 require "util.helpers"
313 pcall(require, "util.signal") -- Not on Windows
315 -- Commented to protect us from
316 -- the second kind of people
318 pcall(require, "remdebug.engine");
319 if remdebug then remdebug.engine.start() end
322 require "net.connlisteners";
324 require "util.stanza"
328 function init_data_store()
329 local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
330 require "util.datamanager".set_data_path(data_path);
331 require "util.datamanager".add_callback(function(username, host, datastore, data)
332 if config.get(host, "core", "anonymous_login") then
335 return username, host, datastore, data;
337 require "core.storagemanager";
340 function prepare_to_start()
341 log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
342 -- Signal to modules that we are ready to start
343 prosody.events.fire_event("server-starting");
345 -- start listening on sockets
346 if config.get("*", "core", "ports") then
347 prosody.net_activate_ports(nil, "multiplex", {5222, 5269});
348 if config.get("*", "core", "ssl_ports") then
349 prosody.net_activate_ports("ssl", "multiplex", {5223}, "ssl");
352 prosody.net_activate_ports("c2s", "xmppclient", {5222});
353 prosody.net_activate_ports("s2s", "xmppserver", {5269});
354 prosody.net_activate_ports("component", "xmppcomponent", {5347}, "tcp");
355 prosody.net_activate_ports("legacy_ssl", "xmppclient", {}, "ssl");
358 prosody.start_time = os.time();
361 function init_global_protection()
362 -- Catch global accesses
363 local locked_globals_mt = {
364 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
365 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
368 function prosody.unlock_globals()
369 setmetatable(_G, nil);
372 function prosody.lock_globals()
373 setmetatable(_G, locked_globals_mt);
377 prosody.lock_globals();
381 -- Error handler for errors that make it this far
382 local function catch_uncaught_error(err)
383 if type(err) == "string" and err:match("interrupted!$") then
387 log("error", "Top-level error, please report:\n%s", tostring(err));
388 local traceback = debug.traceback("", 2);
390 log("error", "%s", traceback);
393 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
396 while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
402 log("info", "Shutdown status: Cleaning up");
403 prosody.events.fire_event("server-cleanup");
405 -- Ok, we're quitting I know, but we
406 -- need to do some tidying before we go :)
407 server.setquitting(false);
409 log("info", "Shutdown status: Closing all active sessions");
410 for hostname, host in pairs(hosts) do
411 log("debug", "Shutdown status: Closing client connections for %s", hostname)
412 if host.sessions then
413 local reason = { condition = "system-shutdown", text = "Server is shutting down" };
414 if prosody.shutdown_reason then
415 reason.text = reason.text..": "..prosody.shutdown_reason;
417 for username, user in pairs(host.sessions) do
418 for resource, session in pairs(user.sessions) do
419 log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
420 session:close(reason);
425 log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
427 for remotehost, session in pairs(host.s2sout) do
428 if session.close then
429 session:close("system-shutdown");
431 log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
437 log("info", "Shutdown status: Closing all server connections");
440 server.setquitting(true);
444 -- These actions are in a strict order, as many depend on
445 -- previous steps to have already been performed
449 set_function_metatable();
453 log("info", "Hello and welcome to Prosody version %s", prosody.version);
454 log_dependency_warnings();
455 load_secondary_libraries();
457 init_global_protection();
460 prosody.events.fire_event("server-started");
464 log("info", "Shutting down...");
466 prosody.events.fire_event("server-stopped");
467 log("info", "Shutdown complete");