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