Merge with Florob
[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(config.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         if not getfenv then
149                 -- FIXME: This is a hack to replace getfenv() in Lua 5.2
150                 function getfenv(f) return debug.getupvalue(debug.getinfo(f or 1).func, 1); end
151         end
152         function require(...)
153                 local curr_env = getfenv(2);
154                 local curr_env_mt = getmetatable(curr_env);
155                 local _realG_mt = getmetatable(_realG);
156                 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
157                         local old_newindex, old_index;
158                         old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
159                         old_index, _realG_mt.__index = _realG_mt.__index, function (_G, k)
160                                 return rawget(curr_env, k);
161                         end;
162                         local ret = _real_require(...);
163                         _realG_mt.__newindex = old_newindex;
164                         _realG_mt.__index = old_index;
165                         return ret;
166                 end
167                 return _real_require(...);
168         end
169 end
170
171 function set_function_metatable()
172         local mt = {};
173         function mt.__index(f, upvalue)
174                 local i, name, value = 0;
175                 repeat
176                         i = i + 1;
177                         name, value = debug.getupvalue(f, i);
178                 until name == upvalue or name == nil;
179                 return value;
180         end
181         function mt.__newindex(f, upvalue, value)
182                 local i, name = 0;
183                 repeat
184                         i = i + 1;
185                         name = debug.getupvalue(f, i);
186                 until name == upvalue or name == nil;
187                 if name then
188                         debug.setupvalue(f, i, value);
189                 end
190         end
191         function mt.__tostring(f)
192                 local info = debug.getinfo(f);
193                 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
194         end
195         debug.setmetatable(function() end, mt);
196 end
197
198 function init_global_state()
199         bare_sessions = {};
200         full_sessions = {};
201         hosts = {};
202
203         prosody.bare_sessions = bare_sessions;
204         prosody.full_sessions = full_sessions;
205         prosody.hosts = hosts;
206         
207         local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
208         local custom_plugin_paths = config.get("*", "core", "plugin_paths");
209         if custom_plugin_paths then
210                 local path_sep = package.config:sub(3,3);
211                 -- path1;path2;path3;defaultpath...
212                 CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
213         end
214         prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR or ".", 
215                           plugins = CFG_PLUGINDIR or "plugins", data = data_path };
216
217         prosody.arg = _G.arg;
218
219         prosody.platform = "unknown";
220         if os.getenv("WINDIR") then
221                 prosody.platform = "windows";
222         elseif package.config:sub(1,1) == "/" then
223                 prosody.platform = "posix";
224         end
225         
226         prosody.installed = nil;
227         if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
228                 prosody.installed = true;
229         end
230         
231         -- Function to reload the config file
232         function prosody.reload_config()
233                 log("info", "Reloading configuration file");
234                 prosody.events.fire_event("reloading-config");
235                 local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
236                 if not ok then
237                         if level == "parser" then
238                                 log("error", "There was an error parsing the configuration file: %s", tostring(err));
239                         elseif level == "file" then
240                                 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
241                         end
242                 end
243                 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
244         end
245
246         -- Function to reopen logfiles
247         function prosody.reopen_logfiles()
248                 log("info", "Re-opening log files");
249                 prosody.events.fire_event("reopen-log-files");
250         end
251
252         -- Function to initiate prosody shutdown
253         function prosody.shutdown(reason)
254                 log("info", "Shutting down: %s", reason or "unknown reason");
255                 prosody.shutdown_reason = reason;
256                 prosody.events.fire_event("server-stopping", {reason = reason});
257                 server.setquitting(true);
258         end
259
260         -- Load SSL settings from config, and create a ctx table
261         local certmanager = require "core.certmanager";
262         local global_ssl_ctx = certmanager.create_context("*", "server");
263         prosody.global_ssl_ctx = global_ssl_ctx;
264
265 end
266
267 function read_version()
268         -- Try to determine version
269         local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
270         if version_file then
271                 prosody.version = version_file:read("*a"):gsub("%s*$", "");
272                 version_file:close();
273                 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
274                         prosody.version = "hg:"..prosody.version;
275                 end
276         else
277                 prosody.version = "unknown";
278         end
279 end
280
281 function load_secondary_libraries()
282         --- Load and initialise core modules
283         require "util.import"
284         require "util.xmppstream"
285         require "core.rostermanager"
286         require "core.stanza_router"
287         require "core.hostmanager"
288         require "core.portmanager"
289         require "core.modulemanager"
290         require "core.usermanager"
291         require "core.sessionmanager"
292         package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
293                 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[ \t]*([^\n]*)"));
294                 return function() end
295         end});
296
297         require "net.http"
298         
299         require "util.array"
300         require "util.datetime"
301         require "util.iterators"
302         require "util.timer"
303         require "util.helpers"
304         
305         pcall(require, "util.signal") -- Not on Windows
306         
307         -- Commented to protect us from 
308         -- the second kind of people
309         --[[ 
310         pcall(require, "remdebug.engine");
311         if remdebug then remdebug.engine.start() end
312         ]]
313
314         require "util.stanza"
315         require "util.jid"
316 end
317
318 function init_data_store()
319         require "core.storagemanager";
320 end
321
322 function prepare_to_start()
323         log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
324         -- Signal to modules that we are ready to start
325         prosody.events.fire_event("server-starting");
326         prosody.start_time = os.time();
327 end     
328
329 function init_global_protection()
330         -- Catch global accesses
331         local locked_globals_mt = {
332                 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
333                 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
334         };
335                 
336         function prosody.unlock_globals()
337                 setmetatable(_G, nil);
338         end
339         
340         function prosody.lock_globals()
341                 setmetatable(_G, locked_globals_mt);
342         end
343
344         -- And lock now...
345         prosody.lock_globals();
346 end
347
348 function loop()
349         -- Error handler for errors that make it this far
350         local function catch_uncaught_error(err)
351                 if type(err) == "string" and err:match("interrupted!$") then
352                         return "quitting";
353                 end
354                 
355                 log("error", "Top-level error, please report:\n%s", tostring(err));
356                 local traceback = debug.traceback("", 2);
357                 if traceback then
358                         log("error", "%s", traceback);
359                 end
360                 
361                 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
362         end
363         
364         while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
365                 socket.sleep(0.2);
366         end
367 end
368
369 function cleanup()
370         log("info", "Shutdown status: Cleaning up");
371         prosody.events.fire_event("server-cleanup");
372         
373         -- Ok, we're quitting I know, but we
374         -- need to do some tidying before we go :)
375         server.setquitting(false);
376         
377         log("info", "Shutdown status: Closing all active sessions");
378         for hostname, host in pairs(hosts) do
379                 log("debug", "Shutdown status: Closing client connections for %s", hostname)
380                 if host.sessions then
381                         local reason = { condition = "system-shutdown", text = "Server is shutting down" };
382                         if prosody.shutdown_reason then
383                                 reason.text = reason.text..": "..prosody.shutdown_reason;
384                         end
385                         for username, user in pairs(host.sessions) do
386                                 for resource, session in pairs(user.sessions) do
387                                         log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
388                                         session:close(reason);
389                                 end
390                         end
391                 end
392         
393                 log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
394                 if host.s2sout then
395                         for remotehost, session in pairs(host.s2sout) do
396                                 if session.close then
397                                         session:close("system-shutdown");
398                                 else
399                                         log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
400                                 end
401                         end
402                 end
403         end
404
405         log("info", "Shutdown status: Closing all server connections");
406         server.closeall();
407         
408         server.setquitting(true);
409 end
410
411 -- Are you ready? :)
412 -- These actions are in a strict order, as many depend on
413 -- previous steps to have already been performed
414 read_config();
415 init_logging();
416 sanity_check();
417 sandbox_require();
418 set_function_metatable();
419 load_libraries();
420 init_global_state();
421 read_version();
422 log("info", "Hello and welcome to Prosody version %s", prosody.version);
423 log_dependency_warnings();
424 load_secondary_libraries();
425 init_data_store();
426 init_global_protection();
427 prepare_to_start();
428
429 prosody.events.fire_event("server-started");
430
431 loop();
432
433 log("info", "Shutting down...");
434 cleanup();
435 prosody.events.fire_event("server-stopped");
436 log("info", "Shutdown complete");
437