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