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