prosody: Catch a recursive Include error and print a more friendly error
[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                         print("");
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...");
86                         else
87                                 print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
88                         end
89                         print("");
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.");
95                 end
96                 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
97                 print("Good luck!");
98                 print("**************************");
99                 print("");
100                 os.exit(1);
101         end
102 end
103
104 function load_libraries()
105         -- Load socket framework
106         server = require "net.server"
107 end     
108
109 function init_logging()
110         -- Initialize logging
111         require "core.loggingmanager"
112 end
113
114 function log_dependency_warnings()
115         dependencies.log_warnings();
116 end
117
118 function sandbox_require()
119         -- Replace require() with one that doesn't pollute _G, required
120         -- for neat sandboxing of modules
121         local _realG = _G;
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
128                         local old_newindex
129                         old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
130                         local ret = _real_require(...);
131                         _realG_mt.__newindex = old_newindex;
132                         return ret;
133                 end
134                 return _real_require(...);
135         end
136 end
137
138 function set_function_metatable()
139         local mt = {};
140         function mt.__index(f, upvalue)
141                 local i, name, value = 0;
142                 repeat
143                         i = i + 1;
144                         name, value = debug.getupvalue(f, i);
145                 until name == upvalue or name == nil;
146                 return value;
147         end
148         function mt.__newindex(f, upvalue, value)
149                 local i, name = 0;
150                 repeat
151                         i = i + 1;
152                         name = debug.getupvalue(f, i);
153                 until name == upvalue or name == nil;
154                 if name then
155                         debug.setupvalue(f, i, value);
156                 end
157         end
158         function mt.__tostring(f)
159                 local info = debug.getinfo(f);
160                 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
161         end
162         debug.setmetatable(function() end, mt);
163 end
164
165 function init_global_state()
166         bare_sessions = {};
167         full_sessions = {};
168         hosts = {};
169
170         prosody.bare_sessions = bare_sessions;
171         prosody.full_sessions = full_sessions;
172         prosody.hosts = hosts;
173         
174         prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
175                           plugins = CFG_PLUGINDIR, data = CFG_DATADIR };
176         
177         prosody.arg = _G.arg;
178
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";
184         end
185         
186         prosody.installed = nil;
187         if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
188                 prosody.installed = true;
189         end
190         
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");
196                 if not ok then
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));
201                         end
202                 end
203                 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
204         end
205
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");
210         end
211
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);
218         end
219
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;
224
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;
232                 
233                 if type(ports) ~= "table" then
234                         log("error", "core."..ports_option.." is not a table");
235                 else
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));
240                                 else
241                                         local ok, err = cl.start(listener, {
242                                                 ssl = conntype == "ssl" and global_ssl_ctx,
243                                                 port = port,
244                                                 interface = (option and config.get("*", "core", option.."_interface"))
245                                                         or cl.get(listener).default_interface
246                                                         or config.get("*", "core", "interface"),
247                                                 type = conntype
248                                         });
249                                         if not ok then
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 "
257                                                                         .."this port";
258                                                         elseif port == 5280 then
259                                                                 friendly_message = "check that Prosody or a BOSH connection manager "
260                                                                         .."is not already running";
261                                                         else
262                                                                 friendly_message = "this port is in use by another application";
263                                                         end
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";
270                                                         else
271                                                                 friendly_message = "initializing SSL support failed, see previous log entries";
272                                                         end
273                                                 end
274                                                 log("error", "Failed to open server port %d, %s", port, friendly_message);
275                                         end
276                                 end
277                         end
278                 end
279         end
280 end
281
282 function read_version()
283         -- Try to determine version
284         local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
285         if version_file then
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;
290                 end
291         else
292                 prosody.version = "unknown";
293         end
294 end
295
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
309         end});
310
311         require "net.http"
312         
313         require "util.array"
314         require "util.datetime"
315         require "util.iterators"
316         require "util.timer"
317         require "util.helpers"
318         
319         pcall(require, "util.signal") -- Not on Windows
320         
321         -- Commented to protect us from 
322         -- the second kind of people
323         --[[ 
324         pcall(require, "remdebug.engine");
325         if remdebug then remdebug.engine.start() end
326         ]]
327
328         require "net.connlisteners";
329         
330         require "util.stanza"
331         require "util.jid"
332 end
333
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 "util.datamanager".add_callback(function(username, host, datastore, data)
338                 if config.get(host, "core", "anonymous_login") then
339                         return false;
340                 end
341                 return username, host, datastore, data;
342         end);
343         require "core.storagemanager";
344 end
345
346 function prepare_to_start()
347         log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
348         -- Signal to modules that we are ready to start
349         prosody.events.fire_event("server-starting");
350
351         -- start listening on sockets
352         if config.get("*", "core", "ports") then
353                 prosody.net_activate_ports(nil, "multiplex", {5222, 5269});
354                 if config.get("*", "core", "ssl_ports") then
355                         prosody.net_activate_ports("ssl", "multiplex", {5223}, "ssl");
356                 end
357         else
358                 prosody.net_activate_ports("c2s", "xmppclient", {5222});
359                 prosody.net_activate_ports("s2s", "xmppserver", {5269});
360                 prosody.net_activate_ports("component", "xmppcomponent", {5347}, "tcp");
361                 prosody.net_activate_ports("legacy_ssl", "xmppclient", {}, "ssl");
362         end
363
364         prosody.start_time = os.time();
365 end     
366
367 function init_global_protection()
368         -- Catch global accesses
369         local locked_globals_mt = {
370                 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
371                 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
372         };
373                 
374         function prosody.unlock_globals()
375                 setmetatable(_G, nil);
376         end
377         
378         function prosody.lock_globals()
379                 setmetatable(_G, locked_globals_mt);
380         end
381
382         -- And lock now...
383         prosody.lock_globals();
384 end
385
386 function loop()
387         -- Error handler for errors that make it this far
388         local function catch_uncaught_error(err)
389                 if type(err) == "string" and err:match("interrupted!$") then
390                         return "quitting";
391                 end
392                 
393                 log("error", "Top-level error, please report:\n%s", tostring(err));
394                 local traceback = debug.traceback("", 2);
395                 if traceback then
396                         log("error", "%s", traceback);
397                 end
398                 
399                 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
400         end
401         
402         while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
403                 socket.sleep(0.2);
404         end
405 end
406
407 function cleanup()
408         log("info", "Shutdown status: Cleaning up");
409         prosody.events.fire_event("server-cleanup");
410         
411         -- Ok, we're quitting I know, but we
412         -- need to do some tidying before we go :)
413         server.setquitting(false);
414         
415         log("info", "Shutdown status: Closing all active sessions");
416         for hostname, host in pairs(hosts) do
417                 log("debug", "Shutdown status: Closing client connections for %s", hostname)
418                 if host.sessions then
419                         local reason = { condition = "system-shutdown", text = "Server is shutting down" };
420                         if prosody.shutdown_reason then
421                                 reason.text = reason.text..": "..prosody.shutdown_reason;
422                         end
423                         for username, user in pairs(host.sessions) do
424                                 for resource, session in pairs(user.sessions) do
425                                         log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
426                                         session:close(reason);
427                                 end
428                         end
429                 end
430         
431                 log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
432                 if host.s2sout then
433                         for remotehost, session in pairs(host.s2sout) do
434                                 if session.close then
435                                         session:close("system-shutdown");
436                                 else
437                                         log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
438                                 end
439                         end
440                 end
441         end
442
443         log("info", "Shutdown status: Closing all server connections");
444         server.closeall();
445         
446         server.setquitting(true);
447 end
448
449 -- Are you ready? :)
450 -- These actions are in a strict order, as many depend on
451 -- previous steps to have already been performed
452 read_config();
453 init_logging();
454 sandbox_require();
455 set_function_metatable();
456 load_libraries();
457 init_global_state();
458 read_version();
459 log("info", "Hello and welcome to Prosody version %s", prosody.version);
460 log_dependency_warnings();
461 load_secondary_libraries();
462 init_data_store();
463 init_global_protection();
464 prepare_to_start();
465
466 prosody.events.fire_event("server-started");
467
468 loop();
469
470 log("info", "Shutting down...");
471 cleanup();
472 prosody.events.fire_event("server-stopped");
473 log("info", "Shutdown complete");
474