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 local prosody = { events = require "util.events".new(); };
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"..":");
82 local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
83 if err:match("chunk has too many syntax levels$") then
84 print("An Include statement in a config file is including an already-included");
85 print("file and causing an infinite loop. An Include statement in a config file is...");
87 print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
90 elseif level == "file" then
91 print("Prosody was unable to find the configuration file.");
92 print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
93 print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
94 print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
96 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
98 print("**************************");
104 function load_libraries()
105 -- Load socket framework
106 server = require "net.server"
109 function init_logging()
110 -- Initialize logging
111 require "core.loggingmanager"
114 function log_dependency_warnings()
115 dependencies.log_warnings();
118 function sandbox_require()
119 -- Replace require() with one that doesn't pollute _G, required
120 -- for neat sandboxing of modules
122 local _real_require = require;
123 function require(...)
124 local curr_env = getfenv(2);
125 local curr_env_mt = getmetatable(getfenv(2));
126 local _realG_mt = getmetatable(_realG);
127 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
129 old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
130 local ret = _real_require(...);
131 _realG_mt.__newindex = old_newindex;
134 return _real_require(...);
138 function set_function_metatable()
140 function mt.__index(f, upvalue)
141 local i, name, value = 0;
144 name, value = debug.getupvalue(f, i);
145 until name == upvalue or name == nil;
148 function mt.__newindex(f, upvalue, value)
152 name = debug.getupvalue(f, i);
153 until name == upvalue or name == nil;
155 debug.setupvalue(f, i, value);
158 function mt.__tostring(f)
159 local info = debug.getinfo(f);
160 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
162 debug.setmetatable(function() end, mt);
165 function init_global_state()
170 prosody.bare_sessions = bare_sessions;
171 prosody.full_sessions = full_sessions;
172 prosody.hosts = hosts;
174 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR,
175 plugins = CFG_PLUGINDIR, data = CFG_DATADIR };
177 prosody.arg = _G.arg;
179 prosody.platform = "unknown";
180 if os.getenv("WINDIR") then
181 prosody.platform = "windows";
182 elseif package.config:sub(1,1) == "/" then
183 prosody.platform = "posix";
186 prosody.installed = nil;
187 if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
188 prosody.installed = true;
191 -- Function to reload the config file
192 function prosody.reload_config()
193 log("info", "Reloading configuration file");
194 prosody.events.fire_event("reloading-config");
195 local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
197 if level == "parser" then
198 log("error", "There was an error parsing the configuration file: %s", tostring(err));
199 elseif level == "file" then
200 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
203 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
206 -- Function to reopen logfiles
207 function prosody.reopen_logfiles()
208 log("info", "Re-opening log files");
209 prosody.events.fire_event("reopen-log-files");
212 -- Function to initiate prosody shutdown
213 function prosody.shutdown(reason)
214 log("info", "Shutting down: %s", reason or "unknown reason");
215 prosody.shutdown_reason = reason;
216 prosody.events.fire_event("server-stopping", {reason = reason});
217 server.setquitting(true);
220 -- Load SSL settings from config, and create a ctx table
221 local certmanager = require "core.certmanager";
222 local global_ssl_ctx = certmanager.create_context("*", "server");
223 prosody.global_ssl_ctx = global_ssl_ctx;
225 local cl = require "net.connlisteners";
226 function prosody.net_activate_ports(option, listener, default, conntype)
227 conntype = conntype or (global_ssl_ctx and "tls") or "tcp";
228 local ports_option = option and option.."_ports" or "ports";
229 if not cl.get(listener) then return; end
230 local ports = config.get("*", "core", ports_option) or default;
231 if type(ports) == "number" then ports = {ports} end;
233 if type(ports) ~= "table" then
234 log("error", "core."..ports_option.." is not a table");
236 for _, port in ipairs(ports) do
237 port = tonumber(port);
238 if type(port) ~= "number" then
239 log("error", "Non-numeric "..ports_option..": "..tostring(port));
241 local ok, err = cl.start(listener, {
242 ssl = conntype == "ssl" and global_ssl_ctx,
244 interface = (option and config.get("*", "core", option.."_interface"))
245 or cl.get(listener).default_interface
246 or config.get("*", "core", "interface"),
250 local friendly_message = err;
251 if err:match(" in use") then
252 if port == 5222 or port == 5223 or port == 5269 then
253 friendly_message = "check that Prosody or another XMPP server is "
254 .."not already running and using this port";
255 elseif port == 80 or port == 81 then
256 friendly_message = "check that a HTTP server is not already using "
258 elseif port == 5280 then
259 friendly_message = "check that Prosody or a BOSH connection manager "
260 .."is not already running";
262 friendly_message = "this port is in use by another application";
264 elseif err:match("permission") then
265 friendly_message = "Prosody does not have sufficient privileges to use this port";
266 elseif err == "no ssl context" then
267 if not config.get("*", "core", "ssl") then
268 friendly_message = "there is no 'ssl' config under Host \"*\" which is "
269 .."require for legacy SSL ports";
271 friendly_message = "initializing SSL support failed, see previous log entries";
274 log("error", "Failed to open server port %d, %s", port, friendly_message);
282 function read_version()
283 -- Try to determine version
284 local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
286 prosody.version = version_file:read("*a"):gsub("%s*$", "");
287 version_file:close();
288 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
289 prosody.version = "hg:"..prosody.version;
292 prosody.version = "unknown";
296 function load_secondary_libraries()
297 --- Load and initialise core modules
298 require "util.import"
299 require "util.xmppstream"
300 require "core.rostermanager"
301 require "core.hostmanager"
302 require "core.modulemanager"
303 require "core.usermanager"
304 require "core.sessionmanager"
305 require "core.stanza_router"
306 package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
307 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[\s\t]*([^\n]*)"));
308 return function() end
314 require "util.datetime"
315 require "util.iterators"
317 require "util.helpers"
319 pcall(require, "util.signal") -- Not on Windows
321 -- Commented to protect us from
322 -- the second kind of people
324 pcall(require, "remdebug.engine");
325 if remdebug then remdebug.engine.start() end
328 require "net.connlisteners";
330 require "util.stanza"
334 function init_data_store()
335 local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
336 require "util.datamanager".set_data_path(data_path);
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");