mod_dialback: Use session:close() on dialback failure instead of s2smanager.destroy_s...
[prosody.git] / prosody
1 #!/usr/bin/env lua
2 -- Prosody IM
3 -- Copyright (C) 2008-2010 Matthew Wild
4 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- 
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
8 --
9
10 -- prosody - main executable for Prosody XMPP server
11
12 -- Will be modified by configure script if run --
13
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");
18
19 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20
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) ~= ":\\")))
25 end
26
27 -- Tell Lua where to find our libraries
28 if CFG_SOURCEDIR then
29         local function filter_relative_paths(path)
30                 if is_relative(path) then return ""; end
31         end
32         local function sanitise_paths(paths)
33                 return (paths:gsub("[^;]+;?", filter_relative_paths):gsub(";;+", ";"));
34         end
35         package.path = sanitise_paths(CFG_SOURCEDIR.."/?.lua;"..package.path);
36         package.cpath = sanitise_paths(CFG_SOURCEDIR.."/?.so;"..package.cpath);
37 end
38
39 -- Substitute ~ with path to home directory in data path
40 if CFG_DATADIR then
41         if os.getenv("HOME") then
42                 CFG_DATADIR = CFG_DATADIR:gsub("^~", os.getenv("HOME"));
43         end
44 end
45
46 -- Global 'prosody' object
47 local prosody = { events = require "util.events".new(); };
48 _G.prosody = prosody;
49
50 -- Check dependencies
51 local dependencies = require "util.dependencies";
52 if not dependencies.check_dependencies() then
53         os.exit(1);
54 end
55
56 -- Load the config-parsing module
57 config = require "core.configmanager"
58
59 -- -- -- --
60 -- Define the functions we call during startup, the 
61 -- actual startup happens right at the end, where these
62 -- functions get called
63
64 function read_config()
65         local filenames = {};
66         
67         local filename;
68         if arg[1] == "--config" and arg[2] then
69                 table.insert(filenames, arg[2]);
70                 if CFG_CONFIGDIR then
71                         table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
72                 end
73         else
74                 for _, format in ipairs(config.parsers()) do
75                         table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
76                 end
77         end
78         for _,_filename in ipairs(filenames) do
79                 filename = _filename;
80                 local file = io.open(filename);
81                 if file then
82                         file:close();
83                         CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
84                         break;
85                 end
86         end
87         local ok, level, err = config.load(filename);
88         if not ok then
89                 print("\n");
90                 print("**************************");
91                 if level == "parser" then
92                         print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua"..":");
93                         print("");
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...");
98                         else
99                                 print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
100                         end
101                         print("");
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.");
107                 end
108                 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
109                 print("Good luck!");
110                 print("**************************");
111                 print("");
112                 os.exit(1);
113         end
114 end
115
116 function load_libraries()
117         -- Load socket framework
118         server = require "net.server"
119 end     
120
121 function init_logging()
122         -- Initialize logging
123         require "core.loggingmanager"
124 end
125
126 function log_dependency_warnings()
127         dependencies.log_warnings();
128 end
129
130 function sandbox_require()
131         -- Replace require() with one that doesn't pollute _G, required
132         -- for neat sandboxing of modules
133         local _realG = _G;
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
140                         local old_newindex
141                         old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
142                         local ret = _real_require(...);
143                         _realG_mt.__newindex = old_newindex;
144                         return ret;
145                 end
146                 return _real_require(...);
147         end
148 end
149
150 function set_function_metatable()
151         local mt = {};
152         function mt.__index(f, upvalue)
153                 local i, name, value = 0;
154                 repeat
155                         i = i + 1;
156                         name, value = debug.getupvalue(f, i);
157                 until name == upvalue or name == nil;
158                 return value;
159         end
160         function mt.__newindex(f, upvalue, value)
161                 local i, name = 0;
162                 repeat
163                         i = i + 1;
164                         name = debug.getupvalue(f, i);
165                 until name == upvalue or name == nil;
166                 if name then
167                         debug.setupvalue(f, i, value);
168                 end
169         end
170         function mt.__tostring(f)
171                 local info = debug.getinfo(f);
172                 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
173         end
174         debug.setmetatable(function() end, mt);
175 end
176
177 function init_global_state()
178         bare_sessions = {};
179         full_sessions = {};
180         hosts = {};
181
182         prosody.bare_sessions = bare_sessions;
183         prosody.full_sessions = full_sessions;
184         prosody.hosts = hosts;
185         
186         local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
187         local custom_plugin_paths = config.get("*", "core", "plugin_paths");
188         if custom_plugin_paths then
189                 local path_sep = package.config:sub(3,3);
190                 -- path1;path2;path3;defaultpath...
191                 CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
192         end
193         prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
194                           plugins = CFG_PLUGINDIR or "plugins", data = data_path };
195
196         prosody.arg = _G.arg;
197
198         prosody.platform = "unknown";
199         if os.getenv("WINDIR") then
200                 prosody.platform = "windows";
201         elseif package.config:sub(1,1) == "/" then
202                 prosody.platform = "posix";
203         end
204         
205         prosody.installed = nil;
206         if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
207                 prosody.installed = true;
208         end
209         
210         -- Function to reload the config file
211         function prosody.reload_config()
212                 log("info", "Reloading configuration file");
213                 prosody.events.fire_event("reloading-config");
214                 local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
215                 if not ok then
216                         if level == "parser" then
217                                 log("error", "There was an error parsing the configuration file: %s", tostring(err));
218                         elseif level == "file" then
219                                 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
220                         end
221                 end
222                 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
223         end
224
225         -- Function to reopen logfiles
226         function prosody.reopen_logfiles()
227                 log("info", "Re-opening log files");
228                 prosody.events.fire_event("reopen-log-files");
229         end
230
231         -- Function to initiate prosody shutdown
232         function prosody.shutdown(reason)
233                 log("info", "Shutting down: %s", reason or "unknown reason");
234                 prosody.shutdown_reason = reason;
235                 prosody.events.fire_event("server-stopping", {reason = reason});
236                 server.setquitting(true);
237         end
238
239         -- Load SSL settings from config, and create a ctx table
240         local certmanager = require "core.certmanager";
241         local global_ssl_ctx = certmanager.create_context("*", "server");
242         prosody.global_ssl_ctx = global_ssl_ctx;
243
244         local cl = require "net.connlisteners";
245         function prosody.net_activate_ports(option, listener, default, conntype)
246                 conntype = conntype or (global_ssl_ctx and "tls") or "tcp";
247                 local ports_option = option and option.."_ports" or "ports";
248                 if not cl.get(listener) then return; end
249                 local ports = config.get("*", "core", ports_option) or default;
250                 if type(ports) == "number" then ports = {ports} end;
251                 
252                 if type(ports) ~= "table" then
253                         log("error", "core."..ports_option.." is not a table");
254                 else
255                         for _, port in ipairs(ports) do
256                                 port = tonumber(port);
257                                 if type(port) ~= "number" then
258                                         log("error", "Non-numeric "..ports_option..": "..tostring(port));
259                                 else
260                                         local ok, err = cl.start(listener, {
261                                                 ssl = conntype == "ssl" and global_ssl_ctx,
262                                                 port = port,
263                                                 interface = (option and config.get("*", "core", option.."_interface"))
264                                                         or cl.get(listener).default_interface
265                                                         or config.get("*", "core", "interface"),
266                                                 type = conntype
267                                         });
268                                         if not ok then
269                                                 local friendly_message = err;
270                                                 if err:match(" in use") then
271                                                         if port == 5222 or port == 5223 or port == 5269 then
272                                                                 friendly_message = "check that Prosody or another XMPP server is "
273                                                                         .."not already running and using this port";
274                                                         elseif port == 80 or port == 81 then
275                                                                 friendly_message = "check that a HTTP server is not already using "
276                                                                         .."this port";
277                                                         elseif port == 5280 then
278                                                                 friendly_message = "check that Prosody or a BOSH connection manager "
279                                                                         .."is not already running";
280                                                         else
281                                                                 friendly_message = "this port is in use by another application";
282                                                         end
283                                                 elseif err:match("permission") then
284                                                         friendly_message = "Prosody does not have sufficient privileges to use this port";
285                                                 elseif err == "no ssl context" then
286                                                         if not config.get("*", "core", "ssl") then
287                                                                 friendly_message = "there is no 'ssl' config under Host \"*\" which is "
288                                                                         .."require for legacy SSL ports";
289                                                         else
290                                                                 friendly_message = "initializing SSL support failed, see previous log entries";
291                                                         end
292                                                 end
293                                                 log("error", "Failed to open server port %d, %s", port, friendly_message);
294                                         end
295                                 end
296                         end
297                 end
298         end
299 end
300
301 function read_version()
302         -- Try to determine version
303         local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
304         if version_file then
305                 prosody.version = version_file:read("*a"):gsub("%s*$", "");
306                 version_file:close();
307                 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
308                         prosody.version = "hg:"..prosody.version;
309                 end
310         else
311                 prosody.version = "unknown";
312         end
313 end
314
315 function load_secondary_libraries()
316         --- Load and initialise core modules
317         require "util.import"
318         require "util.xmppstream"
319         require "core.rostermanager"
320         require "core.hostmanager"
321         require "core.modulemanager"
322         require "core.usermanager"
323         require "core.sessionmanager"
324         require "core.stanza_router"
325         package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
326                 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[\s\t]*([^\n]*)"));
327                 return function() end
328         end});
329
330         require "net.http"
331         
332         require "util.array"
333         require "util.datetime"
334         require "util.iterators"
335         require "util.timer"
336         require "util.helpers"
337         
338         pcall(require, "util.signal") -- Not on Windows
339         
340         -- Commented to protect us from 
341         -- the second kind of people
342         --[[ 
343         pcall(require, "remdebug.engine");
344         if remdebug then remdebug.engine.start() end
345         ]]
346
347         require "net.connlisteners";
348         require "net.httpserver";
349         
350         require "util.stanza"
351         require "util.jid"
352 end
353
354 function init_data_store()
355         require "core.storagemanager";
356 end
357
358 function prepare_to_start()
359         log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
360         -- Signal to modules that we are ready to start
361         prosody.events.fire_event("server-starting");
362
363         -- start listening on sockets
364         if config.get("*", "core", "ports") then
365                 prosody.net_activate_ports(nil, "multiplex", {5222, 5269});
366                 if config.get("*", "core", "ssl_ports") then
367                         prosody.net_activate_ports("ssl", "multiplex", {5223}, "ssl");
368                 end
369         else
370                 prosody.net_activate_ports("c2s", "xmppclient", {5222});
371                 prosody.net_activate_ports("s2s", "xmppserver", {5269});
372                 prosody.net_activate_ports("component", "xmppcomponent", {5347}, "tcp");
373                 prosody.net_activate_ports("legacy_ssl", "xmppclient", {}, "ssl");
374         end
375
376         prosody.start_time = os.time();
377 end     
378
379 function init_global_protection()
380         -- Catch global accesses
381         local locked_globals_mt = {
382                 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
383                 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
384         };
385                 
386         function prosody.unlock_globals()
387                 setmetatable(_G, nil);
388         end
389         
390         function prosody.lock_globals()
391                 setmetatable(_G, locked_globals_mt);
392         end
393
394         -- And lock now...
395         prosody.lock_globals();
396 end
397
398 function loop()
399         -- Error handler for errors that make it this far
400         local function catch_uncaught_error(err)
401                 if type(err) == "string" and err:match("interrupted!$") then
402                         return "quitting";
403                 end
404                 
405                 log("error", "Top-level error, please report:\n%s", tostring(err));
406                 local traceback = debug.traceback("", 2);
407                 if traceback then
408                         log("error", "%s", traceback);
409                 end
410                 
411                 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
412         end
413         
414         while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
415                 socket.sleep(0.2);
416         end
417 end
418
419 function cleanup()
420         log("info", "Shutdown status: Cleaning up");
421         prosody.events.fire_event("server-cleanup");
422         
423         -- Ok, we're quitting I know, but we
424         -- need to do some tidying before we go :)
425         server.setquitting(false);
426         
427         log("info", "Shutdown status: Closing all active sessions");
428         for hostname, host in pairs(hosts) do
429                 log("debug", "Shutdown status: Closing client connections for %s", hostname)
430                 if host.sessions then
431                         local reason = { condition = "system-shutdown", text = "Server is shutting down" };
432                         if prosody.shutdown_reason then
433                                 reason.text = reason.text..": "..prosody.shutdown_reason;
434                         end
435                         for username, user in pairs(host.sessions) do
436                                 for resource, session in pairs(user.sessions) do
437                                         log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
438                                         session:close(reason);
439                                 end
440                         end
441                 end
442         
443                 log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
444                 if host.s2sout then
445                         for remotehost, session in pairs(host.s2sout) do
446                                 if session.close then
447                                         session:close("system-shutdown");
448                                 else
449                                         log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
450                                 end
451                         end
452                 end
453         end
454
455         log("info", "Shutdown status: Closing all server connections");
456         server.closeall();
457         
458         server.setquitting(true);
459 end
460
461 -- Are you ready? :)
462 -- These actions are in a strict order, as many depend on
463 -- previous steps to have already been performed
464 read_config();
465 init_logging();
466 sandbox_require();
467 set_function_metatable();
468 load_libraries();
469 init_global_state();
470 read_version();
471 log("info", "Hello and welcome to Prosody version %s", prosody.version);
472 log_dependency_warnings();
473 load_secondary_libraries();
474 init_data_store();
475 init_global_protection();
476 prepare_to_start();
477
478 prosody.events.fire_event("server-started");
479
480 loop();
481
482 log("info", "Shutting down...");
483 cleanup();
484 prosody.events.fire_event("server-stopped");
485 log("info", "Shutdown complete");
486