prosody, prosodyctl, util.dependencies: Split checking and logging of dependencies...
[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 -- Tell Lua where to find our libraries
22 if CFG_SOURCEDIR then
23         package.path = CFG_SOURCEDIR.."/?.lua;"..package.path;
24         package.cpath = CFG_SOURCEDIR.."/?.so;"..package.cpath;
25 end
26
27 -- Substitute ~ with path to home directory in data path
28 if CFG_DATADIR then
29         if os.getenv("HOME") then
30                 CFG_DATADIR = CFG_DATADIR:gsub("^~", os.getenv("HOME"));
31         end
32 end
33
34 -- Global 'prosody' object
35 prosody = { events = require "util.events".new(); };
36 local prosody = prosody;
37
38 -- Check dependencies
39 local dependencies = require "util.dependencies";
40 if not dependencies.check_dependencies() then
41         os.exit(1);
42 end
43
44 -- Load the config-parsing module
45 config = require "core.configmanager"
46
47 -- -- -- --
48 -- Define the functions we call during startup, the 
49 -- actual startup happens right at the end, where these
50 -- functions get called
51
52 function read_config()
53         local filenames = {};
54         
55         local filename;
56         if arg[1] == "--config" and arg[2] then
57                 table.insert(filenames, arg[2]);
58                 if CFG_CONFIGDIR then
59                         table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
60                 end
61         else
62                 for _, format in ipairs(config.parsers()) do
63                         table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
64                 end
65         end
66         for _,_filename in ipairs(filenames) do
67                 filename = _filename;
68                 local file = io.open(filename);
69                 if file then
70                         file:close();
71                         CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
72                         break;
73                 end
74         end
75         local ok, level, err = config.load(filename);
76         if not ok then
77                 print("\n");
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)));
83                         print("");
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.");
89                 end
90                 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
91                 print("Good luck!");
92                 print("**************************");
93                 print("");
94                 os.exit(1);
95         end
96 end
97
98 function load_libraries()
99         -- Load socket framework
100         server = require "net.server"
101 end     
102
103 function init_logging()
104         -- Initialize logging
105         require "core.loggingmanager"
106 end
107
108 function log_dependency_warnings()
109         dependencies.log_warnings();
110 end
111
112 function sandbox_require()
113         -- Replace require() with one that doesn't pollute _G, required
114         -- for neat sandboxing of modules
115         local _realG = _G;
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
122                         local old_newindex
123                         old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
124                         local ret = _real_require(...);
125                         _realG_mt.__newindex = old_newindex;
126                         return ret;
127                 end
128                 return _real_require(...);
129         end
130 end
131
132 function set_function_metatable()
133         local mt = {};
134         function mt.__index(f, upvalue)
135                 local i, name, value = 0;
136                 repeat
137                         i = i + 1;
138                         name, value = debug.getupvalue(f, i);
139                 until name == upvalue or name == nil;
140                 return value;
141         end
142         function mt.__newindex(f, upvalue, value)
143                 local i, name = 0;
144                 repeat
145                         i = i + 1;
146                         name = debug.getupvalue(f, i);
147                 until name == upvalue or name == nil;
148                 if name then
149                         debug.setupvalue(f, i, value);
150                 end
151         end
152         function mt.__tostring(f)
153                 local info = debug.getinfo(f);
154                 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
155         end
156         debug.setmetatable(function() end, mt);
157 end
158
159 function init_global_state()
160         bare_sessions = {};
161         full_sessions = {};
162         hosts = {};
163
164         prosody.bare_sessions = bare_sessions;
165         prosody.full_sessions = full_sessions;
166         prosody.hosts = hosts;
167         
168         prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
169                           plugins = CFG_PLUGINDIR, data = CFG_DATADIR };
170         
171         prosody.arg = _G.arg;
172
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";
178         end
179         
180         prosody.installed = nil;
181         if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
182                 prosody.installed = true;
183         end
184         
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");
190                 if not ok then
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));
195                         end
196                 end
197                 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
198         end
199
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");
204         end
205
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);
212         end
213
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;
218
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;
226                 
227                 if type(ports) ~= "table" then
228                         log("error", "core."..ports_option.." is not a table");
229                 else
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));
234                                 else
235                                         local ok, err = cl.start(listener, {
236                                                 ssl = conntype == "ssl" and global_ssl_ctx,
237                                                 port = port,
238                                                 interface = (option and config.get("*", "core", option.."_interface"))
239                                                         or cl.get(listener).default_interface
240                                                         or config.get("*", "core", "interface"),
241                                                 type = conntype
242                                         });
243                                         if not ok then
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 "
251                                                                         .."this port";
252                                                         elseif port == 5280 then
253                                                                 friendly_message = "check that Prosody or a BOSH connection manager "
254                                                                         .."is not already running";
255                                                         else
256                                                                 friendly_message = "this port is in use by another application";
257                                                         end
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";
264                                                         else
265                                                                 friendly_message = "initializing SSL support failed, see previous log entries";
266                                                         end
267                                                 end
268                                                 log("error", "Failed to open server port %d, %s", port, friendly_message);
269                                         end
270                                 end
271                         end
272                 end
273         end
274 end
275
276 function read_version()
277         -- Try to determine version
278         local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
279         if version_file then
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;
284                 end
285         else
286                 prosody.version = "unknown";
287         end
288 end
289
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
303         end});
304
305         require "net.http"
306         
307         require "util.array"
308         require "util.datetime"
309         require "util.iterators"
310         require "util.timer"
311         require "util.helpers"
312         
313         pcall(require, "util.signal") -- Not on Windows
314         
315         -- Commented to protect us from 
316         -- the second kind of people
317         --[[ 
318         pcall(require, "remdebug.engine");
319         if remdebug then remdebug.engine.start() end
320         ]]
321
322         require "net.connlisteners";
323         
324         require "util.stanza"
325         require "util.jid"
326 end
327
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
333                         return false;
334                 end
335                 return username, host, datastore, data;
336         end);
337         require "core.storagemanager";
338 end
339
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");
344
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");
350                 end
351         else
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");
356         end
357
358         prosody.start_time = os.time();
359 end     
360
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;
366         };
367                 
368         function prosody.unlock_globals()
369                 setmetatable(_G, nil);
370         end
371         
372         function prosody.lock_globals()
373                 setmetatable(_G, locked_globals_mt);
374         end
375
376         -- And lock now...
377         prosody.lock_globals();
378 end
379
380 function loop()
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
384                         return "quitting";
385                 end
386                 
387                 log("error", "Top-level error, please report:\n%s", tostring(err));
388                 local traceback = debug.traceback("", 2);
389                 if traceback then
390                         log("error", "%s", traceback);
391                 end
392                 
393                 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
394         end
395         
396         while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
397                 socket.sleep(0.2);
398         end
399 end
400
401 function cleanup()
402         log("info", "Shutdown status: Cleaning up");
403         prosody.events.fire_event("server-cleanup");
404         
405         -- Ok, we're quitting I know, but we
406         -- need to do some tidying before we go :)
407         server.setquitting(false);
408         
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;
416                         end
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);
421                                 end
422                         end
423                 end
424         
425                 log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
426                 if host.s2sout then
427                         for remotehost, session in pairs(host.s2sout) do
428                                 if session.close then
429                                         session:close("system-shutdown");
430                                 else
431                                         log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
432                                 end
433                         end
434                 end
435         end
436
437         log("info", "Shutdown status: Closing all server connections");
438         server.closeall();
439         
440         server.setquitting(true);
441 end
442
443 -- Are you ready? :)
444 -- These actions are in a strict order, as many depend on
445 -- previous steps to have already been performed
446 read_config();
447 init_logging();
448 sandbox_require();
449 set_function_metatable();
450 load_libraries();
451 init_global_state();
452 read_version();
453 log("info", "Hello and welcome to Prosody version %s", prosody.version);
454 log_dependency_warnings();
455 load_secondary_libraries();
456 init_data_store();
457 init_global_protection();
458 prepare_to_start();
459
460 prosody.events.fire_event("server-started");
461
462 loop();
463
464 log("info", "Shutting down...");
465 cleanup();
466 prosody.events.fire_event("server-stopped");
467 log("info", "Shutdown complete");
468