Merge Tobias->trunk
[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 -- Load the config-parsing module
39 config = require "core.configmanager"
40
41 -- -- -- --
42 -- Define the functions we call during startup, the 
43 -- actual startup happens right at the end, where these
44 -- functions get called
45
46 function read_config()
47         local filenames = {};
48         
49         local filename;
50         if arg[1] == "--config" and arg[2] then
51                 table.insert(filenames, arg[2]);
52                 if CFG_CONFIGDIR then
53                         table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
54                 end
55         else
56                 for _, format in ipairs(config.parsers()) do
57                         table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
58                 end
59         end
60         for _,_filename in ipairs(filenames) do
61                 filename = _filename;
62                 local file = io.open(filename);
63                 if file then
64                         file:close();
65                         CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
66                         break;
67                 end
68         end
69         local ok, level, err = config.load(filename);
70         if not ok then
71                 print("\n");
72                 print("**************************");
73                 if level == "parser" then
74                         print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
75                         local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
76                         print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
77                         print("");
78                 elseif level == "file" then
79                         print("Prosody was unable to find the configuration file.");
80                         print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
81                         print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
82                         print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
83                 end
84                 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
85                 print("Good luck!");
86                 print("**************************");
87                 print("");
88                 os.exit(1);
89         end
90 end
91
92 function load_libraries()
93         -- Load socket framework
94         server = require "net.server"
95 end     
96
97 function init_logging()
98         -- Initialize logging
99         require "core.loggingmanager"
100 end
101
102 function check_dependencies()
103         -- Check runtime dependencies
104         if not require "util.dependencies".check_dependencies() then
105                 os.exit(1);
106         end
107 end
108
109 function sandbox_require()
110         -- Replace require() with one that doesn't pollute _G, required
111         -- for neat sandboxing of modules
112         local _realG = _G;
113         local _real_require = require;
114         function require(...)
115                 local curr_env = getfenv(2);
116                 local curr_env_mt = getmetatable(getfenv(2));
117                 local _realG_mt = getmetatable(_realG);
118                 if curr_env_mt and curr_env_mt.__index and not curr_env_mt.__newindex and _realG_mt then
119                         local old_newindex
120                         old_newindex, _realG_mt.__newindex = _realG_mt.__newindex, curr_env;
121                         local ret = _real_require(...);
122                         _realG_mt.__newindex = old_newindex;
123                         return ret;
124                 end
125                 return _real_require(...);
126         end
127 end
128
129 function set_function_metatable()
130         local mt = {};
131         function mt.__index(f, upvalue)
132                 local i, name, value = 0;
133                 repeat
134                         i = i + 1;
135                         name, value = debug.getupvalue(f, i);
136                 until name == upvalue or name == nil;
137                 return value;
138         end
139         function mt.__newindex(f, upvalue, value)
140                 local i, name = 0;
141                 repeat
142                         i = i + 1;
143                         name = debug.getupvalue(f, i);
144                 until name == upvalue or name == nil;
145                 if name then
146                         debug.setupvalue(f, i, value);
147                 end
148         end
149         function mt.__tostring(f)
150                 local info = debug.getinfo(f);
151                 return ("function(%s:%d)"):format(info.short_src:match("[^\\/]*$"), info.linedefined);
152         end
153         debug.setmetatable(function() end, mt);
154 end
155
156 function init_global_state()
157         bare_sessions = {};
158         full_sessions = {};
159         hosts = {};
160
161         prosody.bare_sessions = bare_sessions;
162         prosody.full_sessions = full_sessions;
163         prosody.hosts = hosts;
164         
165         prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
166                           plugins = CFG_PLUGINDIR, data = CFG_DATADIR };
167         
168         prosody.arg = _G.arg;
169
170         prosody.platform = "unknown";
171         if os.getenv("WINDIR") then
172                 prosody.platform = "windows";
173         elseif package.config:sub(1,1) == "/" then
174                 prosody.platform = "posix";
175         end
176         
177         prosody.installed = nil;
178         if CFG_SOURCEDIR and (prosody.platform == "windows" or CFG_SOURCEDIR:match("^/")) then
179                 prosody.installed = true;
180         end
181         
182         -- Function to reload the config file
183         function prosody.reload_config()
184                 log("info", "Reloading configuration file");
185                 prosody.events.fire_event("reloading-config");
186                 local ok, level, err = config.load((rawget(_G, "CFG_CONFIGDIR") or ".").."/prosody.cfg.lua");
187                 if not ok then
188                         if level == "parser" then
189                                 log("error", "There was an error parsing the configuration file: %s", tostring(err));
190                         elseif level == "file" then
191                                 log("error", "Couldn't read the config file when trying to reload: %s", tostring(err));
192                         end
193                 end
194                 return ok, (err and tostring(level)..": "..tostring(err)) or nil;
195         end
196
197         -- Function to reopen logfiles
198         function prosody.reopen_logfiles()
199                 log("info", "Re-opening log files");
200                 prosody.events.fire_event("reopen-log-files");
201         end
202
203         -- Function to initiate prosody shutdown
204         function prosody.shutdown(reason)
205                 log("info", "Shutting down: %s", reason or "unknown reason");
206                 prosody.shutdown_reason = reason;
207                 prosody.events.fire_event("server-stopping", {reason = reason});
208                 server.setquitting(true);
209         end
210
211         -- Load SSL settings from config, and create a ctx table
212         local certmanager = require "core.certmanager";
213         local global_ssl_ctx = certmanager.create_context("*", "server");
214         prosody.global_ssl_ctx = global_ssl_ctx;
215
216         local cl = require "net.connlisteners";
217         function prosody.net_activate_ports(option, listener, default, conntype)
218                 conntype = conntype or (global_ssl_ctx and "tls") or "tcp";
219                 local ports_option = option and option.."_ports" or "ports";
220                 if not cl.get(listener) then return; end
221                 local ports = config.get("*", "core", ports_option) or default;
222                 if type(ports) == "number" then ports = {ports} end;
223                 
224                 if type(ports) ~= "table" then
225                         log("error", "core."..ports_option.." is not a table");
226                 else
227                         for _, port in ipairs(ports) do
228                                 port = tonumber(port);
229                                 if type(port) ~= "number" then
230                                         log("error", "Non-numeric "..ports_option..": "..tostring(port));
231                                 else
232                                         local ok, err = cl.start(listener, {
233                                                 ssl = conntype == "ssl" and global_ssl_ctx,
234                                                 port = port,
235                                                 interface = (option and config.get("*", "core", option.."_interface"))
236                                                         or cl.get(listener).default_interface
237                                                         or config.get("*", "core", "interface"),
238                                                 type = conntype
239                                         });
240                                         if not ok then
241                                                 local friendly_message = err;
242                                                 if err:match(" in use") then
243                                                         if port == 5222 or port == 5223 or port == 5269 then
244                                                                 friendly_message = "check that Prosody or another XMPP server is "
245                                                                         .."not already running and using this port";
246                                                         elseif port == 80 or port == 81 then
247                                                                 friendly_message = "check that a HTTP server is not already using "
248                                                                         .."this port";
249                                                         elseif port == 5280 then
250                                                                 friendly_message = "check that Prosody or a BOSH connection manager "
251                                                                         .."is not already running";
252                                                         else
253                                                                 friendly_message = "this port is in use by another application";
254                                                         end
255                                                 elseif err:match("permission") then
256                                                         friendly_message = "Prosody does not have sufficient privileges to use this port";
257                                                 elseif err == "no ssl context" then
258                                                         if not config.get("*", "core", "ssl") then
259                                                                 friendly_message = "there is no 'ssl' config under Host \"*\" which is "
260                                                                         .."require for legacy SSL ports";
261                                                         else
262                                                                 friendly_message = "initializing SSL support failed, see previous log entries";
263                                                         end
264                                                 end
265                                                 log("error", "Failed to open server port %d, %s", port, friendly_message);
266                                         end
267                                 end
268                         end
269                 end
270         end
271 end
272
273 function read_version()
274         -- Try to determine version
275         local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
276         if version_file then
277                 prosody.version = version_file:read("*a"):gsub("%s*$", "");
278                 version_file:close();
279                 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
280                         prosody.version = "hg:"..prosody.version;
281                 end
282         else
283                 prosody.version = "unknown";
284         end
285 end
286
287 function load_secondary_libraries()
288         --- Load and initialise core modules
289         require "util.import"
290         require "util.xmppstream"
291         require "core.rostermanager"
292         require "core.hostmanager"
293         require "core.modulemanager"
294         require "core.usermanager"
295         require "core.sessionmanager"
296         require "core.stanza_router"
297         package.loaded['core.componentmanager'] = setmetatable({},{__index=function()
298                 log("warn", "componentmanager is deprecated: %s", debug.traceback():match("\n[^\n]*\n[\s\t]*([^\n]*)"));
299                 return function() end
300         end});
301
302         require "net.http"
303         
304         require "util.array"
305         require "util.datetime"
306         require "util.iterators"
307         require "util.timer"
308         require "util.helpers"
309         
310         pcall(require, "util.signal") -- Not on Windows
311         
312         -- Commented to protect us from 
313         -- the second kind of people
314         --[[ 
315         pcall(require, "remdebug.engine");
316         if remdebug then remdebug.engine.start() end
317         ]]
318
319         require "net.connlisteners";
320         
321         require "util.stanza"
322         require "util.jid"
323 end
324
325 function init_data_store()
326         local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
327         require "util.datamanager".set_data_path(data_path);
328         require "util.datamanager".add_callback(function(username, host, datastore, data)
329                 if config.get(host, "core", "anonymous_login") then
330                         return false;
331                 end
332                 return username, host, datastore, data;
333         end);
334         require "core.storagemanager";
335 end
336
337 function prepare_to_start()
338         log("info", "Prosody is using the %s backend for connection handling", server.get_backend());
339         -- Signal to modules that we are ready to start
340         prosody.events.fire_event("server-starting");
341
342         -- start listening on sockets
343         if config.get("*", "core", "ports") then
344                 prosody.net_activate_ports(nil, "multiplex", {5222, 5269});
345                 if config.get("*", "core", "ssl_ports") then
346                         prosody.net_activate_ports("ssl", "multiplex", {5223}, "ssl");
347                 end
348         else
349                 prosody.net_activate_ports("c2s", "xmppclient", {5222});
350                 prosody.net_activate_ports("s2s", "xmppserver", {5269});
351                 prosody.net_activate_ports("component", "xmppcomponent", {5347}, "tcp");
352                 prosody.net_activate_ports("legacy_ssl", "xmppclient", {}, "ssl");
353         end
354
355         prosody.start_time = os.time();
356 end     
357
358 function init_global_protection()
359         -- Catch global accesses
360         local locked_globals_mt = {
361                 __index = function (t, k) log("warn", "%s", debug.traceback("Attempt to read a non-existent global '"..tostring(k).."'", 2)); end;
362                 __newindex = function (t, k, v) error("Attempt to set a global: "..tostring(k).." = "..tostring(v), 2); end;
363         };
364                 
365         function prosody.unlock_globals()
366                 setmetatable(_G, nil);
367         end
368         
369         function prosody.lock_globals()
370                 setmetatable(_G, locked_globals_mt);
371         end
372
373         -- And lock now...
374         prosody.lock_globals();
375 end
376
377 function loop()
378         -- Error handler for errors that make it this far
379         local function catch_uncaught_error(err)
380                 if type(err) == "string" and err:match("interrupted!$") then
381                         return "quitting";
382                 end
383                 
384                 log("error", "Top-level error, please report:\n%s", tostring(err));
385                 local traceback = debug.traceback("", 2);
386                 if traceback then
387                         log("error", "%s", traceback);
388                 end
389                 
390                 prosody.events.fire_event("very-bad-error", {error = err, traceback = traceback});
391         end
392         
393         while select(2, xpcall(server.loop, catch_uncaught_error)) ~= "quitting" do
394                 socket.sleep(0.2);
395         end
396 end
397
398 function cleanup()
399         log("info", "Shutdown status: Cleaning up");
400         prosody.events.fire_event("server-cleanup");
401         
402         -- Ok, we're quitting I know, but we
403         -- need to do some tidying before we go :)
404         server.setquitting(false);
405         
406         log("info", "Shutdown status: Closing all active sessions");
407         for hostname, host in pairs(hosts) do
408                 log("debug", "Shutdown status: Closing client connections for %s", hostname)
409                 if host.sessions then
410                         local reason = { condition = "system-shutdown", text = "Server is shutting down" };
411                         if prosody.shutdown_reason then
412                                 reason.text = reason.text..": "..prosody.shutdown_reason;
413                         end
414                         for username, user in pairs(host.sessions) do
415                                 for resource, session in pairs(user.sessions) do
416                                         log("debug", "Closing connection for %s@%s/%s", username, hostname, resource);
417                                         session:close(reason);
418                                 end
419                         end
420                 end
421         
422                 log("debug", "Shutdown status: Closing outgoing s2s connections from %s", hostname);
423                 if host.s2sout then
424                         for remotehost, session in pairs(host.s2sout) do
425                                 if session.close then
426                                         session:close("system-shutdown");
427                                 else
428                                         log("warn", "Unable to close outgoing s2s session to %s, no session:close()?!", remotehost);
429                                 end
430                         end
431                 end
432         end
433
434         log("info", "Shutdown status: Closing all server connections");
435         server.closeall();
436         
437         server.setquitting(true);
438 end
439
440 -- Are you ready? :)
441 -- These actions are in a strict order, as many depend on
442 -- previous steps to have already been performed
443 read_config();
444 init_logging();
445 check_dependencies();
446 sandbox_require();
447 set_function_metatable();
448 load_libraries();
449 init_global_state();
450 read_version();
451 log("info", "Hello and welcome to Prosody version %s", prosody.version);
452 load_secondary_libraries();
453 init_data_store();
454 init_global_protection();
455 prepare_to_start();
456
457 prosody.events.fire_event("server-started");
458
459 loop();
460
461 log("info", "Shutting down...");
462 cleanup();
463 prosody.events.fire_event("server-stopped");
464 log("info", "Shutdown complete");
465