Let Google Hangouts contacts appear offline
[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 sanity_check()
131         for host, host_config in pairs(configmanager.getconfig()) do
132                 if host ~= "*"
133                 and host_config.core.enabled ~= false
134                 and not host_config.core.component_module then
135                         return;
136                 end
137         end
138         log("error", "No enabled VirtualHost entries found in the config file.");
139         log("error", "At least one active host is required for Prosody to function. Exiting...");
140         os.exit(1);
141 end
142
143 function sandbox_require()
144         -- Replace require() with one that doesn't pollute _G, required
145         -- for neat sandboxing of modules
146         local _realG = _G;
147         local _real_require = require;
148         function require(...)
149                 local curr_env = getfenv(2);
150                 local curr_env_mt = getmetatable(getfenv(2));
151                 local _realG_mt = getmetatable(_realG);
152                 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
153                         local old_newindex
154                         old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
155                         local ret = _real_require(...);
156                         _realG_mt.__newindex = old_newindex;
157                         return ret;
158                 end
159                 return _real_require(...);
160         end
161 end
162
163 function set_function_metatable()
164         local mt = {};
165         function mt.__index(f, upvalue)
166                 local i, name, value = 0;
167                 repeat
168                         i = i + 1;
169                         name, value = debug.getupvalue(f, i);
170                 until name == upvalue or name == nil;
171                 return value;
172         end
173         function mt.__newindex(f, upvalue, value)
174                 local i, name = 0;
175                 repeat
176                         i = i + 1;
177                         name = debug.getupvalue(f, i);
178                 until name == upvalue or name == nil;
179                 if name then
180                         debug.setupvalue(f, i, value);
181                 end
182         end
183         function mt.__tostring(f)
184                 local info = debug.getinfo(f);
185                 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
186         end
187         debug.setmetatable(function() end, mt);
188 end
189
190 function init_global_state()
191         bare_sessions = {};
192         full_sessions = {};
193         hosts = {};
194
195         prosody.bare_sessions = bare_sessions;
196         prosody.full_sessions = full_sessions;
197         prosody.hosts = hosts;
198         
199         local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
200         local custom_plugin_paths = config.get("*", "core", "plugin_paths");
201         if custom_plugin_paths then
202                 local path_sep = package.config:sub(3,3);
203                 -- path1;path2;path3;defaultpath...
204                 CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
205         end
206         prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
207                           plugins = CFG_PLUGINDIR or "plugins", data = data_path };
208
209         prosody.arg = _G.arg;
210
211         prosody.platform = "unknown";
212         if os.getenv("WINDIR") then
213                 prosody.platform = "windows";
214         elseif package.config:sub(1,1) == "/" then
215                 prosody.platform = "posix";
216         end
217         
218         prosody.installed = nil;
219         if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
220                 prosody.installed = true;
221         end
222         
223         -- Function to reload the config file
224         function prosody.reload_config()
225                 log("info", "Reloading configuration file");
226                 prosody.events.fire_event("reloading-config");
227                 local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
228                 if not ok then
229                         if level == "parser" then
230                                 log("error", "There was an error parsing the configuration file: %s", tostring(err));
231                         elseif level == "file" then
232                                 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
233                         end
234                 end
235                 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
236         end
237
238         -- Function to reopen logfiles
239         function prosody.reopen_logfiles()
240                 log("info", "Re-opening log files");
241                 prosody.events.fire_event("reopen-log-files");
242         end
243
244         -- Function to initiate prosody shutdown
245         function prosody.shutdown(reason)
246                 log("info", "Shutting down: %s", reason or "unknown reason");
247                 prosody.shutdown_reason = reason;
248                 prosody.events.fire_event("server-stopping", {reason = reason});
249                 server.setquitting(true);
250         end
251
252         -- Load SSL settings from config, and create a ctx table
253         local certmanager = require "core.certmanager";
254         local global_ssl_ctx = certmanager.create_context("*", "server");
255         prosody.global_ssl_ctx = global_ssl_ctx;
256
257         local cl = require "net.connlisteners";
258         function prosody.net_activate_ports(option, listener, default, conntype)
259                 conntype = conntype or (global_ssl_ctx and "tls") or "tcp";
260                 local ports_option = option and option.."_ports" or "ports";
261                 if not cl.get(listener) then return; end
262                 local ports = config.get("*", "core", ports_option) or default;
263                 if type(ports) == "number" then ports = {ports} end;
264                 
265                 if type(ports) ~= "table" then
266                         log("error", "core."..ports_option.." is not a table");
267                 else
268                         for _, port in ipairs(ports) do
269                                 port = tonumber(port);
270                                 if type(port) ~= "number" then
271                                         log("error", "Non-numeric "..ports_option..": "..tostring(port));
272                                 else
273                                         local ok, err = cl.start(listener, {
274                                                 ssl = conntype == "ssl" and global_ssl_ctx,
275                                                 port = port,
276                                                 interface = (option and config.get("*", "core", option.."_interface"))
277                                                         or cl.get(listener).default_interface
278                                                         or config.get("*", "core", "interface"),
279                                                 type = conntype
280                                         });
281                                         if not ok then
282                                                 local friendly_message = err;
283                                                 if err:match(" in use") then
284                                                         if port == 5222 or port == 5223 or port == 5269 then
285                                                                 friendly_message = "check that Prosody or another XMPP server is "
286                                                                         .."not already running and using this port";
287                                                         elseif port == 80 or port == 81 then
288                                                                 friendly_message = "check that a HTTP server is not already using "
289                                                                         .."this port";
290                                                         elseif port == 5280 then
291                                                                 friendly_message = "check that Prosody or a BOSH connection manager "
292                                                                         .."is not already running";
293                                                         else
294                                                                 friendly_message = "this port is in use by another application";
295                                                         end
296                                                 elseif err:match("permission") then
297                                                         friendly_message = "Prosody does not have sufficient privileges to use this port";
298                                                 elseif err == "no ssl context" then
299                                                         if not config.get("*", "core", "ssl") then
300                                                                 friendly_message = "there is no 'ssl' config under Host \"*\" which is "
301                                                                         .."require for legacy SSL ports";
302                                                         else
303                                                                 friendly_message = "initializing SSL support failed, see previous log entries";
304                                                         end
305                                                 end
306                                                 log("error", "Failed to open server port %d, %s", port, friendly_message);
307                                         end
308                                 end
309                         end
310                 end
311         end
312 end
313
314 function read_version()
315         -- Try to determine version
316         local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
317         if version_file then
318                 prosody.version = version_file:read("*a"):gsub("%s*$", "");
319                 version_file:close();
320                 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
321                         prosody.version = "hg:"..prosody.version;
322                 end
323         else
324                 prosody.version = "unknown";
325         end
326 end
327
328 function load_secondary_libraries()
329         --- Load and initialise core modules
330         require "util.import"
331         require "util.xmppstream"
332         require "core.rostermanager"
333         require "core.hostmanager"
334         require "core.modulemanager"
335         require "core.usermanager"
336         require "core.sessionmanager"
337         require "core.stanza_router"
338         package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
339                 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[\s\t]*([^\n]*)"));
340                 return function() end
341         end});
342
343         require "net.http"
344         
345         require "util.array"
346         require "util.datetime"
347         require "util.iterators"
348         require "util.timer"
349         require "util.helpers"
350         
351         pcall(require, "util.signal") -- Not on Windows
352         
353         -- Commented to protect us from 
354         -- the second kind of people
355         --[[ 
356         pcall(require, "remdebug.engine");
357         if remdebug then remdebug.engine.start() end
358         ]]
359
360         require "net.connlisteners";
361         require "net.httpserver";
362         
363         require "util.stanza"
364         require "util.jid"
365 end
366
367 function init_data_store()
368         require "core.storagemanager";
369 end
370
371 function prepare_to_start()
372         log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
373         -- Signal to modules that we are ready to start
374         prosody.events.fire_event("server-starting");
375
376         -- start listening on sockets
377         if config.get("*", "core", "ports") then
378                 prosody.net_activate_ports(nil, "multiplex", {5222, 5269});
379                 if config.get("*", "core", "ssl_ports") then
380                         prosody.net_activate_ports("ssl", "multiplex", {5223}, "ssl");
381                 end
382         else
383                 prosody.net_activate_ports("c2s", "xmppclient", {5222});
384                 prosody.net_activate_ports("s2s", "xmppserver", {5269});
385                 prosody.net_activate_ports("component", "xmppcomponent", {5347}, "tcp");
386                 prosody.net_activate_ports("legacy_ssl", "xmppclient", {}, "ssl");
387         end
388
389         prosody.start_time = os.time();
390 end     
391
392 function init_global_protection()
393         -- Catch global accesses
394         local locked_globals_mt = {
395                 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
396                 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
397         };
398                 
399         function prosody.unlock_globals()
400                 setmetatable(_G, nil);
401         end
402         
403         function prosody.lock_globals()
404                 setmetatable(_G, locked_globals_mt);
405         end
406
407         -- And lock now...
408         prosody.lock_globals();
409 end
410
411 function loop()
412         -- Error handler for errors that make it this far
413         local function catch_uncaught_error(err)
414                 if type(err) == "string" and err:match("interrupted!$") then
415                         return "quitting";
416                 end
417                 
418                 log("error", "Top-level error, please report:\n%s", tostring(err));
419                 local traceback = debug.traceback("", 2);
420                 if traceback then
421                         log("error", "%s", traceback);
422                 end
423                 
424                 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
425         end
426         
427         while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
428                 socket.sleep(0.2);
429         end
430 end
431
432 function cleanup()
433         log("info", "Shutdown status: Cleaning up");
434         prosody.events.fire_event("server-cleanup");
435         
436         -- Ok, we're quitting I know, but we
437         -- need to do some tidying before we go :)
438         server.setquitting(false);
439         
440         log("info", "Shutdown status: Closing all active sessions");
441         for hostname, host in pairs(hosts) do
442                 log("debug", "Shutdown status: Closing client connections for %s", hostname)
443                 if host.sessions then
444                         local reason = { condition = "system-shutdown", text = "Server is shutting down" };
445                         if prosody.shutdown_reason then
446                                 reason.text = reason.text..": "..prosody.shutdown_reason;
447                         end
448                         for username, user in pairs(host.sessions) do
449                                 for resource, session in pairs(user.sessions) do
450                                         log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
451                                         session:close(reason);
452                                 end
453                         end
454                 end
455         
456                 log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
457                 if host.s2sout then
458                         for remotehost, session in pairs(host.s2sout) do
459                                 if session.close then
460                                         session:close("system-shutdown");
461                                 else
462                                         log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
463                                 end
464                         end
465                 end
466         end
467
468         log("info", "Shutdown status: Closing all server connections");
469         server.closeall();
470         
471         server.setquitting(true);
472 end
473
474 -- Are you ready? :)
475 -- These actions are in a strict order, as many depend on
476 -- previous steps to have already been performed
477 read_config();
478 init_logging();
479 sanity_check();
480 sandbox_require();
481 set_function_metatable();
482 load_libraries();
483 init_global_state();
484 read_version();
485 log("info", "Hello and welcome to Prosody version %s", prosody.version);
486 log_dependency_warnings();
487 load_secondary_libraries();
488 init_data_store();
489 init_global_protection();
490 prepare_to_start();
491
492 prosody.events.fire_event("server-started");
493
494 loop();
495
496 log("info", "Shutting down...");
497 cleanup();
498 prosody.events.fire_event("server-stopped");
499 log("info", "Shutdown complete");
500