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