mod_presence: Re-probe for contacts presence after outgoing 'subscribed' (fixes ...
[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
53 -- Load the config-parsing module
54 config = require "core.configmanager"
55
56 -- -- -- --
57 -- Define the functions we call during startup, the 
58 -- actual startup happens right at the end, where these
59 -- functions get called
60
61 function read_config()
62         local filenames = {};
63         
64         local filename;
65         if arg[1] == "--config" and arg[2] then
66                 table.insert(filenames, arg[2]);
67                 if CFG_CONFIGDIR then
68                         table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
69                 end
70         elseif os.getenv("PROSODY_CONFIG") then -- Passed by prosodyctl
71                         table.insert(filenames, os.getenv("PROSODY_CONFIG"));
72         else
73                 for _, format in ipairs(config.parsers()) do
74                         table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
75                 end
76         end
77         for _,_filename in ipairs(filenames) do
78                 filename = _filename;
79                 local file = io.open(filename);
80                 if file then
81                         file:close();
82                         CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
83                         break;
84                 end
85         end
86         prosody.config_file = filename
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 check_dependencies()
117         if not dependencies.check_dependencies() then
118                 os.exit(1);
119         end
120 end
121
122 function load_libraries()
123         -- Load socket framework
124         server = require "net.server"
125 end     
126
127 function init_logging()
128         -- Initialize logging
129         require "core.loggingmanager"
130 end
131
132 function log_dependency_warnings()
133         dependencies.log_warnings();
134 end
135
136 function sanity_check()
137         for host, host_config in pairs(config.getconfig()) do
138                 if host ~= "*"
139                 and host_config.enabled ~= false
140                 and not host_config.component_module then
141                         return;
142                 end
143         end
144         log("error", "No enabled VirtualHost entries found in the config file.");
145         log("error", "At least one active host is required for Prosody to function. Exiting...");
146         os.exit(1);
147 end
148
149 function sandbox_require()
150         -- Replace require() with one that doesn't pollute _G, required
151         -- for neat sandboxing of modules
152         local _realG = _G;
153         local _real_require = require;
154         if not getfenv then
155                 -- FIXME: This is a hack to replace getfenv() in Lua 5.2
156                 function getfenv(f) return debug.getupvalue(debug.getinfo(f or 1).func, 1); end
157         end
158         function require(...)
159                 local curr_env = getfenv(2);
160                 local curr_env_mt = getmetatable(curr_env);
161                 local _realG_mt = getmetatable(_realG);
162                 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
163                         local old_newindex, old_index;
164                         old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
165                         old_index, _realG_mt.__index = _realG_mt.__index, function (_G, k)
166                                 return rawget(curr_env, k);
167                         end;
168                         local ret = _real_require(...);
169                         _realG_mt.__newindex = old_newindex;
170                         _realG_mt.__index = old_index;
171                         return ret;
172                 end
173                 return _real_require(...);
174         end
175 end
176
177 function set_function_metatable()
178         local mt = {};
179         function mt.__index(f, upvalue)
180                 local i, name, value = 0;
181                 repeat
182                         i = i + 1;
183                         name, value = debug.getupvalue(f, i);
184                 until name == upvalue or name == nil;
185                 return value;
186         end
187         function mt.__newindex(f, upvalue, value)
188                 local i, name = 0;
189                 repeat
190                         i = i + 1;
191                         name = debug.getupvalue(f, i);
192                 until name == upvalue or name == nil;
193                 if name then
194                         debug.setupvalue(f, i, value);
195                 end
196         end
197         function mt.__tostring(f)
198                 local info = debug.getinfo(f);
199                 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
200         end
201         debug.setmetatable(function() end, mt);
202 end
203
204 function init_global_state()
205         -- COMPAT: These globals are deprecated
206         bare_sessions = {};
207         full_sessions = {};
208         hosts = {};
209
210         prosody.bare_sessions = bare_sessions;
211         prosody.full_sessions = full_sessions;
212         prosody.hosts = hosts;
213         
214         local data_path = config.get("*", "data_path") or CFG_DATADIR or "data";
215         local custom_plugin_paths = config.get("*", "plugin_paths");
216         if custom_plugin_paths then
217                 local path_sep = package.config:sub(3,3);
218                 -- path1;path2;path3;defaultpath...
219                 CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
220         end
221         prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR or ".", 
222                           plugins = CFG_PLUGINDIR or "plugins", data = data_path };
223
224         prosody.arg = _G.arg;
225
226         prosody.platform = "unknown";
227         if os.getenv("WINDIR") then
228                 prosody.platform = "windows";
229         elseif package.config:sub(1,1) == "/" then
230                 prosody.platform = "posix";
231         end
232         
233         prosody.installed = nil;
234         if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
235                 prosody.installed = true;
236         end
237         
238         if prosody.installed then
239                 -- Change working directory to data path.
240                 require "lfs".chdir(data_path);
241         end
242
243         -- Function to reload the config file
244         function prosody.reload_config()
245                 log("info", "Reloading configuration file");
246                 prosody.events.fire_event("reloading-config");
247                 local ok, level, err = config.load(prosody.config_file);
248                 if not ok then
249                         if level == "parser" then
250                                 log("error", "There was an error parsing the configuration file: %s", tostring(err));
251                         elseif level == "file" then
252                                 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
253                         end
254                 end
255                 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
256         end
257
258         -- Function to reopen logfiles
259         function prosody.reopen_logfiles()
260                 log("info", "Re-opening log files");
261                 prosody.events.fire_event("reopen-log-files");
262         end
263
264         -- Function to initiate prosody shutdown
265         function prosody.shutdown(reason)
266                 log("info", "Shutting down: %s", reason or "unknown reason");
267                 prosody.shutdown_reason = reason;
268                 prosody.events.fire_event("server-stopping", {reason = reason});
269                 server.setquitting(true);
270         end
271
272         -- Load SSL settings from config, and create a ctx table
273         local certmanager = require "core.certmanager";
274         local global_ssl_ctx = certmanager.create_context("*", "server");
275         prosody.global_ssl_ctx = global_ssl_ctx;
276
277 end
278
279 function read_version()
280         -- Try to determine version
281         local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
282         if version_file then
283                 prosody.version = version_file:read("*a"):gsub("%s*$", "");
284                 version_file:close();
285                 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
286                         prosody.version = "hg:"..prosody.version;
287                 end
288         else
289                 prosody.version = "unknown";
290         end
291 end
292
293 function load_secondary_libraries()
294         --- Load and initialise core modules
295         require "util.import"
296         require "util.xmppstream"
297         require "core.stanza_router"
298         require "core.hostmanager"
299         require "core.portmanager"
300         require "core.modulemanager"
301         require "core.usermanager"
302         require "core.rostermanager"
303         require "core.sessionmanager"
304         package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
305                 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[ \t]*([^\n]*)"));
306                 return function() end
307         end});
308
309         require "net.http"
310         
311         require "util.array"
312         require "util.datetime"
313         require "util.iterators"
314         require "util.timer"
315         require "util.helpers"
316         
317         pcall(require, "util.signal") -- Not on Windows
318         
319         -- Commented to protect us from 
320         -- the second kind of people
321         --[[ 
322         pcall(require, "remdebug.engine");
323         if remdebug then remdebug.engine.start() end
324         ]]
325
326         require "util.stanza"
327         require "util.jid"
328 end
329
330 function init_data_store()
331         require "core.storagemanager";
332 end
333
334 function prepare_to_start()
335         log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
336         -- Signal to modules that we are ready to start
337         prosody.events.fire_event("server-starting");
338         prosody.start_time = os.time();
339 end     
340
341 function init_global_protection()
342         -- Catch global accesses
343         local locked_globals_mt = {
344                 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
345                 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
346         };
347                 
348         function prosody.unlock_globals()
349                 setmetatable(_G, nil);
350         end
351         
352         function prosody.lock_globals()
353                 setmetatable(_G, locked_globals_mt);
354         end
355
356         -- And lock now...
357         prosody.lock_globals();
358 end
359
360 function loop()
361         -- Error handler for errors that make it this far
362         local function catch_uncaught_error(err)
363                 if type(err) == "string" and err:match("interrupted!$") then
364                         return "quitting";
365                 end
366                 
367                 log("error", "Top-level error, please report:\n%s", tostring(err));
368                 local traceback = debug.traceback("", 2);
369                 if traceback then
370                         log("error", "%s", traceback);
371                 end
372                 
373                 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
374         end
375         
376         while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
377                 socket.sleep(0.2);
378         end
379 end
380
381 function cleanup()
382         log("info", "Shutdown status: Cleaning up");
383         prosody.events.fire_event("server-cleanup");
384 end
385
386 -- Are you ready? :)
387 -- These actions are in a strict order, as many depend on
388 -- previous steps to have already been performed
389 read_config();
390 init_logging();
391 sanity_check();
392 sandbox_require();
393 set_function_metatable();
394 check_dependencies();
395 load_libraries();
396 init_global_state();
397 read_version();
398 log("info", "Hello and welcome to Prosody version %s", prosody.version);
399 log_dependency_warnings();
400 load_secondary_libraries();
401 init_data_store();
402 init_global_protection();
403 prepare_to_start();
404
405 prosody.events.fire_event("server-started");
406
407 loop();
408
409 log("info", "Shutting down...");
410 cleanup();
411 prosody.events.fire_event("server-stopped");
412 log("info", "Shutdown complete");
413