3 -- Copyright (C) 2008-2010 Matthew Wild
4 -- Copyright (C) 2008-2010 Waqas Hussain
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
10 -- prosodyctl - command-line controller for Prosody XMPP server
12 -- Will be modified by configure script if run --
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");
19 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
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) ~= ":\\")))
27 -- Tell Lua where to find our libraries
29 local function filter_relative_paths(path)
30 if is_relative(path) then return ""; end
32 local function sanitise_paths(paths)
33 return (paths:gsub("[^;]+;?", filter_relative_paths):gsub(";;+", ";"));
35 package.path = sanitise_paths(CFG_SOURCEDIR.."/?.lua;"..package.path);
36 package.cpath = sanitise_paths(CFG_SOURCEDIR.."/?.so;"..package.cpath);
39 -- Substitute ~ with path to home directory in data path
41 if os.getenv("HOME") then
42 CFG_DATADIR = CFG_DATADIR:gsub("^~", os.getenv("HOME"));
46 -- Global 'prosody' object
49 events = require "util.events".new();
51 lock_globals = function () end;
52 unlock_globals = function () end;
53 installed = CFG_SOURCEDIR ~= nil;
54 core_post_stanza = function () end; -- TODO: mod_router!
58 local dependencies = require "util.dependencies";
59 if not dependencies.check_dependencies() then
63 config = require "core.configmanager"
70 if arg[1] == "--config" and arg[2] then
71 table.insert(filenames, arg[2]);
73 table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
75 table.remove(arg, 1); table.remove(arg, 1);
77 for _, format in ipairs(config.parsers()) do
78 table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
81 for _,_filename in ipairs(filenames) do
83 local file = io.open(filename);
86 ENV_CONFIG = filename;
87 CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
91 local ok, level, err = config.load(filename);
94 print("**************************");
95 if level == "parser" then
96 print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
97 local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
98 print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
100 elseif level == "file" then
101 print("Prosody was unable to find the configuration file.");
102 print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
103 print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
104 print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
106 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
108 print("**************************");
113 local original_logging_config = config.get("*", "log");
114 config.set("*", "log", { { levels = { min="info" }, to = "console" } });
116 local data_path = config.get("*", "data_path") or CFG_DATADIR or "data";
117 local custom_plugin_paths = config.get("*", "plugin_paths");
118 if custom_plugin_paths then
119 local path_sep = package.config:sub(3,3);
120 -- path1;path2;path3;defaultpath...
121 CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
123 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR,
124 plugins = CFG_PLUGINDIR or "plugins", data = data_path };
126 if prosody.installed then
127 -- Change working directory to data path.
128 require "lfs".chdir(data_path);
131 require "core.loggingmanager"
133 dependencies.log_warnings();
135 -- Switch away from root and into the prosody user --
136 local switched_user, current_uid;
138 local want_pposix_version = "0.3.6";
139 local ok, pposix = pcall(require, "util.pposix");
141 if ok and pposix then
142 if pposix._VERSION ~= want_pposix_version then print(string.format("Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version)); return; end
143 current_uid = pposix.getuid();
144 if current_uid == 0 then
146 local desired_user = config.get("*", "prosody_user") or "prosody";
147 local desired_group = config.get("*", "prosody_group") or desired_user;
148 local ok, err = pposix.setgid(desired_group);
150 ok, err = pposix.initgroups(desired_user);
153 ok, err = pposix.setuid(desired_user);
156 switched_user = true;
159 if not switched_user then
161 print("Warning: Couldn't switch to Prosody user/group '"..tostring(desired_user).."'/'"..tostring(desired_group).."': "..tostring(err));
165 -- Set our umask to protect data files
166 pposix.umask(config.get("*", "umask") or "027");
167 pposix.setenv("HOME", data_path);
168 pposix.setenv("PROSODY_CONFIG", ENV_CONFIG);
170 print("Error: Unable to load pposix module. Check that Prosody is installed correctly.")
171 print("For more help send the below error to us through http://prosody.im/discuss");
172 print(tostring(pposix))
176 local function test_writeable(filename)
177 local f, err = io.open(filename, "a");
185 local unwriteable_files = {};
186 if type(original_logging_config) == "string" and original_logging_config:sub(1,1) ~= "*" then
187 local ok, err = test_writeable(original_logging_config);
189 table.insert(unwriteable_files, err);
191 elseif type(original_logging_config) == "table" then
192 for _, rule in ipairs(original_logging_config) do
193 if rule.filename then
194 local ok, err = test_writeable(rule.filename);
196 table.insert(unwriteable_files, err);
202 if #unwriteable_files > 0 then
203 print("One of more of the Prosody log files are not");
204 print("writeable, please correct the errors and try");
205 print("starting prosodyctl again.");
207 for _, err in ipairs(unwriteable_files) do
215 local error_messages = setmetatable({
216 ["invalid-username"] = "The given username is invalid in a Jabber ID";
217 ["invalid-hostname"] = "The given hostname is invalid";
218 ["no-password"] = "No password was supplied";
219 ["no-such-user"] = "The given user does not exist on the server";
220 ["no-such-host"] = "The given hostname does not exist in the config";
221 ["unable-to-save-data"] = "Unable to store, perhaps you don't have permission?";
222 ["no-pidfile"] = "There is no 'pidfile' option in the configuration file, see http://prosody.im/doc/prosodyctl#pidfile for help";
223 ["invalid-pidfile"] = "The 'pidfile' option in the configuration file is not a string, see http://prosody.im/doc/prosodyctl#pidfile for help";
224 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see http://prosody.im/doc/prosodyctl for more info";
225 ["no-such-method"] = "This module has no commands";
226 ["not-running"] = "Prosody is not running";
227 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
229 hosts = prosody.hosts;
231 local function make_host(hostname)
234 events = prosody.events,
236 users = require "core.usermanager".new_null_provider(hostname)
240 for hostname, config in pairs(config.getconfig()) do
241 hosts[hostname] = make_host(hostname);
244 local modulemanager = require "core.modulemanager"
246 local prosodyctl = require "util.prosodyctl"
248 -----------------------
250 -- FIXME: Duplicate code waiting for util.startup
251 function read_version()
252 -- Try to determine version
253 local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
254 prosody.version = "unknown";
256 prosody.version = version_file:read("*a"):gsub("%s*$", "");
257 version_file:close();
258 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
259 prosody.version = "hg:"..prosody.version;
262 local hg = require"util.mercurial";
263 local hgid = hg.check_id(CFG_SOURCEDIR or ".");
264 if hgid then prosody.version = "hg:" .. hgid; end
268 local show_message, show_warning = prosodyctl.show_message, prosodyctl.show_warning;
269 local show_usage = prosodyctl.show_usage;
270 local getchar, getpass = prosodyctl.getchar, prosodyctl.getpass;
271 local show_yesno = prosodyctl.show_yesno;
272 local show_prompt = prosodyctl.show_prompt;
273 local read_password = prosodyctl.read_password;
275 local jid_split = require "util.jid".prepped_split;
277 local prosodyctl_timeout = (config.get("*", "prosodyctl_timeout") or 5) * 2;
278 -----------------------
280 local command = arg[1];
282 function commands.adduser(arg)
283 if not arg[1] or arg[1] == "--help" then
284 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
287 local user, host = jid_split(arg[1]);
288 if not user and host then
289 show_message [[Failed to understand JID, please supply the JID you want to create]]
290 show_usage [[adduser user@host]]
295 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
299 if not hosts[host] then
300 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
301 show_warning("The user will not be able to log in until this is changed.");
302 hosts[host] = make_host(host);
305 if prosodyctl.user_exists{ user = user, host = host } then
306 show_message [[That user already exists]];
310 local password = read_password();
311 if not password then return 1; end
313 local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
315 if ok then return 0; end
321 function commands.passwd(arg)
322 if not arg[1] or arg[1] == "--help" then
323 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
326 local user, host = jid_split(arg[1]);
327 if not user and host then
328 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
329 show_usage [[passwd user@host]]
334 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
338 if not hosts[host] then
339 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
340 show_warning("The user will not be able to log in until this is changed.");
341 hosts[host] = make_host(host);
344 if not prosodyctl.user_exists { user = user, host = host } then
345 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
349 local password = read_password();
350 if not password then return 1; end
352 local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
354 if ok then return 0; end
356 show_message(error_messages[msg])
360 function commands.deluser(arg)
361 if not arg[1] or arg[1] == "--help" then
362 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
365 local user, host = jid_split(arg[1]);
366 if not user and host then
367 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
368 show_usage [[passwd user@host]]
373 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
377 if not hosts[host] then
378 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
379 hosts[host] = make_host(host);
382 if not prosodyctl.user_exists { user = user, host = host } then
383 show_message [[That user does not exist on this server]]
387 local ok, msg = prosodyctl.deluser { user = user, host = host };
389 if ok then return 0; end
391 show_message(error_messages[msg])
395 function commands.start(arg)
396 if arg[1] == "--help" then
397 show_usage([[start]], [[Start Prosody]]);
400 local ok, ret = prosodyctl.isrunning();
402 show_message(error_messages[ret]);
407 local ok, ret = prosodyctl.getpid();
409 show_message("Couldn't get running Prosody's PID");
410 show_message(error_messages[ret]);
413 show_message("Prosody is already running with PID %s", ret or "(unknown)");
417 local ok, ret = prosodyctl.start();
419 local daemonize = config.get("*", "daemonize");
420 if daemonize == nil then
421 daemonize = prosody.installed;
426 local ok, running = prosodyctl.isrunning();
427 if ok and running then
430 show_message("Still waiting...");
431 elseif i >= prosodyctl_timeout then
432 show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
438 show_message("Started");
443 show_message("Failed to start Prosody");
444 show_message(error_messages[ret])
448 function commands.status(arg)
449 if arg[1] == "--help" then
450 show_usage([[status]], [[Reports the running status of Prosody]]);
454 local ok, ret = prosodyctl.isrunning();
456 show_message(error_messages[ret]);
461 local ok, ret = prosodyctl.getpid();
463 show_message("Couldn't get running Prosody's PID");
464 show_message(error_messages[ret]);
467 show_message("Prosody is running with PID %s", ret or "(unknown)");
470 show_message("Prosody is not running");
471 if not switched_user and current_uid ~= 0 then
473 print(" You will also see this if prosodyctl is not running under");
474 print(" the same user account as Prosody. Try running as root (e.g. ");
475 print(" with 'sudo' in front) to gain access to Prosody's real status.");
482 function commands.stop(arg)
483 if arg[1] == "--help" then
484 show_usage([[stop]], [[Stop a running Prosody server]]);
488 if not prosodyctl.isrunning() then
489 show_message("Prosody is not running");
493 local ok, ret = prosodyctl.stop();
497 local ok, running = prosodyctl.isrunning();
498 if ok and not running then
501 show_message("Still waiting...");
502 elseif i >= prosodyctl_timeout then
503 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
509 show_message("Stopped");
513 show_message(error_messages[ret]);
517 function commands.restart(arg)
518 if arg[1] == "--help" then
519 show_usage([[restart]], [[Restart a running Prosody server]]);
524 return commands.start(arg);
527 function commands.about(arg)
529 if arg[1] == "--help" then
530 show_usage([[about]], [[Show information about this Prosody installation]]);
535 local lfs = require "lfs";
536 local array = require "util.array";
537 local keys = require "util.iterators".keys;
538 local hg = require"util.mercurial";
539 local relpath = config.resolve_relative_path;
541 print("Prosody "..(prosody.version or "(unknown version)"));
543 print("# Prosody directories");
544 print("Data directory: "..relpath(pwd, data_path));
545 print("Config directory: "..relpath(pwd, CFG_CONFIGDIR or "."));
546 print("Source directory: "..relpath(pwd, CFG_SOURCEDIR or "."));
547 print("Plugin directories:")
548 print(" "..(prosody.paths.plugins:gsub("([^;]+);?", function(path)
550 path = config.resolve_relative_path(pwd, path);
551 local hgid, hgrepo = hg.check_id(path);
552 if not hgid and hgrepo then
553 return path.." - "..hgrepo .."!\n ";
555 -- 010452cfaf53 is the first commit in the prosody-modules repository
556 hgrepo = hgrepo == "010452cfaf53" and "prosody-modules";
557 return path..(hgid and " - "..(hgrepo or "HG").." rev: "..hgid or "")
561 print("# Lua environment");
562 print("Lua version: ", _G._VERSION);
564 print("Lua module search paths:");
565 for path in package.path:gmatch("[^;]+") do
569 print("Lua C module search paths:");
570 for path in package.cpath:gmatch("[^;]+") do
574 local luarocks_status = (pcall(require, "luarocks.loader") and "Installed ("..(package.loaded["luarocks.cfg"].program_version or "2.x+")..")")
575 or (pcall(require, "luarocks.require") and "Installed (1.x)")
577 print("LuaRocks: ", luarocks_status);
579 print("# Lua module versions");
580 local module_versions, longest_name = {}, 8;
581 local luaevent =dependencies.softreq"luaevent";
582 local ssl = dependencies.softreq"ssl";
583 for name, module in pairs(package.loaded) do
584 if type(module) == "table" and rawget(module, "_VERSION")
585 and name ~= "_G" and not name:match("%.") then
586 if #name > longest_name then
587 longest_name = #name;
589 module_versions[name] = module._VERSION;
592 local sorted_keys = array.collect(keys(module_versions)):sort();
593 for _, name in ipairs(array.collect(keys(module_versions)):sort()) do
594 print(name..":"..string.rep(" ", longest_name-#name), module_versions[name]);
599 function commands.reload(arg)
600 if arg[1] == "--help" then
601 show_usage([[reload]], [[Reload Prosody's configuration and re-open log files]]);
605 if not prosodyctl.isrunning() then
606 show_message("Prosody is not running");
610 local ok, ret = prosodyctl.reload();
613 show_message("Prosody log files re-opened and config file reloaded. You may need to reload modules for some changes to take effect.");
617 show_message(error_messages[ret]);
620 -- ejabberdctl compatibility
622 function commands.register(arg)
623 local user, host, password = unpack(arg);
624 if (not (user and host)) or arg[1] == "--help" then
625 if user ~= "--help" then
627 show_message [[No username specified]]
629 show_message [[Please specify which host you want to register the user on]];
632 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
636 password = read_password();
638 show_message [[Unable to register user with no password]];
643 local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
645 if ok then return 0; end
647 show_message(error_messages[msg])
651 function commands.unregister(arg)
652 local user, host = unpack(arg);
653 if (not (user and host)) or arg[1] == "--help" then
654 if user ~= "--help" then
656 show_message [[No username specified]]
658 show_message [[Please specify which host you want to unregister the user from]];
661 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
665 local ok, msg = prosodyctl.deluser { user = user, host = host };
667 if ok then return 0; end
669 show_message(error_messages[msg])
676 local cert_commands = {};
678 local function ask_overwrite(filename)
679 return lfs.attributes(filename) and not show_yesno("Overwrite "..filename .. "?");
682 function cert_commands.config(arg)
683 if #arg >= 1 and arg[1] ~= "--help" then
684 local conf_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".cnf";
685 if ask_overwrite(conf_filename) then
686 return nil, conf_filename;
688 local conf = openssl.config.new();
689 conf:from_prosody(hosts, config, arg);
690 show_message("Please provide details to include in the certificate config file.");
691 show_message("Leave the field empty to use the default value or '.' to exclude the field.")
692 for i, k in ipairs(openssl._DN_order) do
693 local v = conf.distinguished_name[k];
696 if k == "commonName" then
698 elseif k == "emailAddress" then
699 v = "xmpp@" .. arg[1];
700 elseif k == "countryName" then
701 local tld = arg[1]:match"%.([a-z]+)$";
702 if tld and #tld == 2 and tld ~= "uk" then
706 nv = show_prompt(("%s (%s):"):format(k, nv or v));
707 nv = (not nv or nv == "") and v or nv;
708 if nv:find"[\192-\252][\128-\191]+" then
709 conf.req.string_mask = "utf8only"
711 conf.distinguished_name[k] = nv ~= "." and nv or nil;
714 local conf_file, err = io.open(conf_filename, "w");
715 if not conf_file then
716 show_warning("Could not open OpenSSL config file for writing");
720 conf_file:write(conf:serialize());
723 show_message("Config written to " .. conf_filename);
724 return nil, conf_filename;
726 show_usage("cert config HOSTNAME [HOSTNAME+]", "Builds a certificate config file covering the supplied hostname(s)")
730 function cert_commands.key(arg)
731 if #arg >= 1 and arg[1] ~= "--help" then
732 local key_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".key";
733 if ask_overwrite(key_filename) then
734 return nil, key_filename;
736 os.remove(key_filename); -- This file, if it exists is unlikely to have write permissions
737 local key_size = tonumber(arg[2] or show_prompt("Choose key size (2048):") or 2048);
738 local old_umask = pposix.umask("0377");
739 if openssl.genrsa{out=key_filename, key_size} then
740 os.execute(("chmod 400 '%s'"):format(key_filename));
741 show_message("Key written to ".. key_filename);
742 pposix.umask(old_umask);
743 return nil, key_filename;
745 show_message("There was a problem, see OpenSSL output");
747 show_usage("cert key HOSTNAME <bits>", "Generates a RSA key named HOSTNAME.key\n "
748 .."Prompts for a key size if none given")
752 function cert_commands.request(arg)
753 if #arg >= 1 and arg[1] ~= "--help" then
754 local req_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".req";
755 if ask_overwrite(req_filename) then
756 return nil, req_filename;
758 local _, key_filename = cert_commands.key({arg[1]});
759 local _, conf_filename = cert_commands.config(arg);
760 if openssl.req{new=true, key=key_filename, utf8=true, sha256=true, config=conf_filename, out=req_filename} then
761 show_message("Certificate request written to ".. req_filename);
763 show_message("There was a problem, see OpenSSL output");
766 show_usage("cert request HOSTNAME [HOSTNAME+]", "Generates a certificate request for the supplied hostname(s)")
770 function cert_commands.generate(arg)
771 if #arg >= 1 and arg[1] ~= "--help" then
772 local cert_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".crt";
773 if ask_overwrite(cert_filename) then
774 return nil, cert_filename;
776 local _, key_filename = cert_commands.key({arg[1]});
777 local _, conf_filename = cert_commands.config(arg);
779 if key_filename and conf_filename and cert_filename
780 and openssl.req{new=true, x509=true, nodes=true, key=key_filename,
781 days=365, sha256=true, utf8=true, config=conf_filename, out=cert_filename} then
782 show_message("Certificate written to ".. cert_filename);
784 show_message("There was a problem, see OpenSSL output");
787 show_usage("cert generate HOSTNAME [HOSTNAME+]", "Generates a self-signed certificate for the current hostname(s)")
791 function commands.cert(arg)
792 if #arg >= 1 and arg[1] ~= "--help" then
793 openssl = require "util.openssl";
795 local subcmd = table.remove(arg, 1);
796 if type(cert_commands[subcmd]) == "function" then
798 show_message"You need to supply at least one hostname"
801 if arg[1] ~= "--help" and not hosts[arg[1]] then
802 show_message(error_messages["no-such-host"]);
805 return cert_commands[subcmd](arg);
808 show_usage("cert config|request|generate|key", "Helpers for generating X.509 certificates and keys.")
811 function commands.check(arg)
812 if arg[1] == "--help" then
813 show_usage([[check]], [[Perform basic checks on your Prosody installation]]);
816 local what = table.remove(arg, 1);
817 local array, set = require "util.array", require "util.set";
818 local it = require "util.iterators";
820 local function disabled_hosts(host, conf) return host ~= "*" and conf.enabled ~= false; end
821 local function enabled_hosts() return it.filter(disabled_hosts, pairs(config.getconfig())); end
822 if not what or what == "disabled" then
823 local disabled_hosts = set.new();
824 for host, host_options in it.filter("*", pairs(config.getconfig())) do
825 if host_options.enabled == false then
826 disabled_hosts:add(host);
829 if not disabled_hosts:empty() then
830 local msg = "Checks will be skipped for these disabled hosts: %s";
831 if what then msg = "These hosts are disabled: %s"; end
832 show_warning(msg, tostring(disabled_hosts));
833 if what then return 0; end
837 if not what or what == "config" then
838 print("Checking config...");
839 local deprecated = set.new({
840 "bosh_ports", "disallow_s2s", "no_daemonize", "anonymous_login", "require_encryption",
842 local known_global_options = set.new({
843 "pidfile", "log", "plugin_paths", "prosody_user", "prosody_group", "daemonize",
844 "umask", "prosodyctl_timeout", "use_ipv6", "use_libevent", "network_settings"
846 local config = config.getconfig();
847 -- Check that we have any global options (caused by putting a host at the top)
848 if it.count(it.filter("log", pairs(config["*"]))) == 0 then
851 print(" No global options defined. Perhaps you have put a host definition at the top")
852 print(" of the config file? They should be at the bottom, see http://prosody.im/doc/configure#overview");
854 if it.count(enabled_hosts()) == 0 then
857 if it.count(it.filter("*", pairs(config))) == 0 then
858 print(" No hosts are defined, please add at least one VirtualHost section")
859 elseif config["*"]["enabled"] == false then
860 print(" No hosts are enabled. Remove enabled = false from the global section or put enabled = true under at least one VirtualHost section")
862 print(" All hosts are disabled. Remove enabled = false from at least one VirtualHost section")
865 -- Check for global options under hosts
866 local global_options = set.new(it.to_array(it.keys(config["*"])));
867 local deprecated_global_options = set.intersection(global_options, deprecated);
868 if not deprecated_global_options:empty() then
870 print(" You have some deprecated options in the global section:");
871 print(" "..tostring(deprecated_global_options))
874 for host, options in enabled_hosts() do
875 local host_options = set.new(it.to_array(it.keys(options)));
876 local misplaced_options = set.intersection(host_options, known_global_options);
877 for name in pairs(options) do
878 if name:match("^interfaces?")
879 or name:match("_ports?$") or name:match("_interfaces?$")
880 or name:match("_ssl$") then
881 misplaced_options:add(name);
884 if not misplaced_options:empty() then
887 local n = it.count(misplaced_options);
888 print(" You have "..n.." option"..(n>1 and "s " or " ").."set under "..host.." that should be");
889 print(" in the global section of the config file, above any VirtualHost or Component definitions,")
890 print(" see http://prosody.im/doc/configure#overview for more information.")
892 print(" You need to move the following option"..(n>1 and "s" or "")..": "..table.concat(it.to_array(misplaced_options), ", "));
894 local subdomain = host:match("^[^.]+");
895 if not(host_options:contains("component_module")) and (subdomain == "jabber" or subdomain == "xmpp"
896 or subdomain == "chat" or subdomain == "im") then
898 print(" Suggestion: If "..host.. " is a new host with no real users yet, consider renaming it now to");
899 print(" "..host:gsub("^[^.]+%.", "")..". You can use SRV records to redirect XMPP clients and servers to "..host..".");
900 print(" For more information see: http://prosody.im/doc/dns");
906 if not what or what == "dns" then
907 local dns = require "net.dns";
908 local idna = require "util.encodings".idna;
909 local ip = require "util.ip";
910 local c2s_ports = set.new(config.get("*", "c2s_ports") or {5222});
911 local s2s_ports = set.new(config.get("*", "s2s_ports") or {5269});
913 local c2s_srv_required, s2s_srv_required;
914 if not c2s_ports:contains(5222) then
915 c2s_srv_required = true;
917 if not s2s_ports:contains(5269) then
918 s2s_srv_required = true;
921 local problem_hosts = set.new();
923 local external_addresses, internal_addresses = set.new(), set.new();
925 local fqdn = socket.dns.tohostname(socket.dns.gethostname());
927 local res = dns.lookup(idna.to_ascii(fqdn), "A");
929 for _, record in ipairs(res) do
930 external_addresses:add(record.a);
933 local res = dns.lookup(idna.to_ascii(fqdn), "AAAA");
935 for _, record in ipairs(res) do
936 external_addresses:add(record.aaaa);
941 local local_addresses = require"util.net".local_addresses() or {};
943 for addr in it.values(local_addresses) do
944 if not ip.new_ip(addr).private then
945 external_addresses:add(addr);
947 internal_addresses:add(addr);
951 if external_addresses:empty() then
953 print(" Failed to determine the external addresses of this server. Checks may be inaccurate.");
954 c2s_srv_required, s2s_srv_required = true, true;
957 local v6_supported = not not socket.tcp6;
959 for host, host_options in enabled_hosts() do
960 local all_targets_ok, some_targets_ok = true, false;
962 local is_component = not not host_options.component_module;
963 print("Checking DNS for "..(is_component and "component" or "host").." "..host.."...");
964 local target_hosts = set.new();
965 if not is_component then
966 local res = dns.lookup("_xmpp-client._tcp."..idna.to_ascii(host)..".", "SRV");
968 for _, record in ipairs(res) do
969 target_hosts:add(record.srv.target);
970 if not c2s_ports:contains(record.srv.port) then
971 print(" SRV target "..record.srv.target.." contains unknown client port: "..record.srv.port);
975 if c2s_srv_required then
976 print(" No _xmpp-client SRV record found for "..host..", but it looks like you need one.");
977 all_targst_ok = false;
979 target_hosts:add(host);
983 local res = dns.lookup("_xmpp-server._tcp."..idna.to_ascii(host)..".", "SRV");
985 for _, record in ipairs(res) do
986 target_hosts:add(record.srv.target);
987 if not s2s_ports:contains(record.srv.port) then
988 print(" SRV target "..record.srv.target.." contains unknown server port: "..record.srv.port);
992 if s2s_srv_required then
993 print(" No _xmpp-server SRV record found for "..host..", but it looks like you need one.");
994 all_targets_ok = false;
996 target_hosts:add(host);
999 if target_hosts:empty() then
1000 target_hosts:add(host);
1003 if target_hosts:contains("localhost") then
1004 print(" Target 'localhost' cannot be accessed from other servers");
1005 target_hosts:remove("localhost");
1008 local modules = set.new(it.to_array(it.values(host_options.modules_enabled)))
1009 + set.new(it.to_array(it.values(config.get("*", "modules_enabled"))))
1010 + set.new({ config.get(host, "component_module") });
1012 if modules:contains("proxy65") then
1013 local proxy65_target = config.get(host, "proxy65_address") or host;
1014 local A, AAAA = dns.lookup(idna.to_ascii(proxy65_target), "A"), dns.lookup(idna.to_ascii(proxy65_target), "AAAA");
1017 table.insert(prob, "A");
1019 if v6_supported and not AAAA then
1020 table.insert(prob, "AAAA");
1023 print(" File transfer proxy "..proxy65_target.." has no "..table.concat(prob, "/").." record. Create one or set 'proxy65_address' to the correct host/IP.");
1027 for host in target_hosts do
1028 local host_ok_v4, host_ok_v6;
1029 local res = dns.lookup(idna.to_ascii(host), "A");
1031 for _, record in ipairs(res) do
1032 if external_addresses:contains(record.a) then
1033 some_targets_ok = true;
1035 elseif internal_addresses:contains(record.a) then
1037 some_targets_ok = true;
1038 print(" "..host.." A record points to internal address, external connections might fail");
1040 print(" "..host.." A record points to unknown address "..record.a);
1041 all_targets_ok = false;
1045 local res = dns.lookup(idna.to_ascii(host), "AAAA");
1047 for _, record in ipairs(res) do
1048 if external_addresses:contains(record.aaaa) then
1049 some_targets_ok = true;
1051 elseif internal_addresses:contains(record.aaaa) then
1053 some_targets_ok = true;
1054 print(" "..host.." AAAA record points to internal address, external connections might fail");
1056 print(" "..host.." AAAA record points to unknown address "..record.aaaa);
1057 all_targets_ok = false;
1062 local bad_protos = {}
1063 if not host_ok_v4 then
1064 table.insert(bad_protos, "IPv4");
1066 if not host_ok_v6 then
1067 table.insert(bad_protos, "IPv6");
1069 if #bad_protos > 0 then
1070 print(" Host "..host.." does not seem to resolve to this server ("..table.concat(bad_protos, "/")..")");
1072 if host_ok_v6 and not v6_supported then
1073 print(" Host "..host.." has AAAA records, but your version of LuaSocket does not support IPv6.");
1074 print(" Please see http://prosody.im/doc/ipv6 for more information.");
1077 if not all_targets_ok then
1078 print(" "..(some_targets_ok and "Only some" or "No").." targets for "..host.." appear to resolve to this server.");
1079 if is_component then
1080 print(" DNS records are necessary if you want users on other servers to access this component.");
1082 problem_hosts:add(host);
1086 if not problem_hosts:empty() then
1088 print("For more information about DNS configuration please see http://prosody.im/doc/dns");
1093 if not what or what == "certs" then
1095 print"Checking certificates..."
1096 local x509_verify_identity = require"util.x509".verify_identity;
1097 local ssl = dependencies.softreq"ssl";
1098 -- local datetime_parse = require"util.datetime".parse_x509;
1099 local load_cert = ssl and ssl.loadcertificate;
1100 -- or ssl.cert_from_pem
1102 print("LuaSec not available, can't perform certificate checks")
1103 if what == "certs" then cert_ok = false end
1104 elseif not load_cert then
1105 print("This version of LuaSec (" .. ssl._VERSION .. ") does not support certificate checking");
1108 for host in enabled_hosts() do
1109 print("Checking certificate for "..host);
1110 -- First, let's find out what certificate this host uses.
1111 local ssl_config = config.rawget(host, "ssl");
1112 if not ssl_config then
1113 local base_host = host:match("%.(.*)");
1114 ssl_config = config.get(base_host, "ssl");
1116 if not ssl_config then
1117 print(" No 'ssl' option defined for "..host)
1119 elseif not ssl_config.certificate then
1120 print(" No 'certificate' set in ssl option for "..host)
1122 elseif not ssl_config.key then
1123 print(" No 'key' set in ssl option for "..host)
1126 local key, err = io.open(ssl_config.key); -- Permissions check only
1128 print(" Could not open "..ssl_config.key..": "..err);
1133 local cert_fh, err = io.open(ssl_config.certificate); -- Load the file.
1135 print(" Could not open "..ssl_config.certificate..": "..err);
1138 print(" Certificate: "..ssl_config.certificate)
1139 local cert = load_cert(cert_fh:read"*a"); cert_fh = cert_fh:close();
1140 if not cert:validat(os.time()) then
1141 print(" Certificate has expired.")
1144 if config.get(host, "component_module") == nil
1145 and not x509_verify_identity(host, "_xmpp-client", cert) then
1146 print(" Not vaild for client connections to "..host..".")
1149 if (not (config.get(host, "anonymous_login")
1150 or config.get(host, "authentication") == "anonymous"))
1151 and not x509_verify_identity(host, "_xmpp-server", cert) then
1152 print(" Not vaild for server-to-server connections to "..host..".")
1158 if cert_ok == false then
1160 print("For more information about certificates please see http://prosody.im/doc/certificates");
1167 print("Problems found, see above.");
1169 print("All checks passed, congratulations!");
1171 return ok and 0 or 2;
1174 ---------------------
1176 if command and command:match("^mod_") then -- Is a command in a module
1177 local module_name = command:match("^mod_(.+)");
1178 local ret, err = modulemanager.load("*", module_name);
1180 show_message("Failed to load module '"..module_name.."': "..err);
1184 table.remove(arg, 1);
1186 local module = modulemanager.get_module("*", module_name);
1188 show_message("Failed to load module '"..module_name.."': Unknown error");
1192 if not modulemanager.module_has_method(module, "command") then
1193 show_message("Fail: mod_"..module_name.." does not support any commands");
1197 local ok, ret = modulemanager.call_module_method(module, "command", arg);
1199 if type(ret) == "number" then
1201 elseif type(ret) == "string" then
1206 show_message("Failed to execute command: "..error_messages[ret]);
1211 if not commands[command] then -- Show help for all commands
1212 function show_usage(usage, desc)
1217 print("prosodyctl - Manage a Prosody server");
1219 print("Usage: "..arg[0].." COMMAND [OPTIONS]");
1221 print("Where COMMAND may be one of:\n");
1223 local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
1224 local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart", "reload", "about" };
1228 for _, command_name in ipairs(commands_order) do
1229 local command = commands[command_name];
1231 command{ "--help" };
1233 done[command_name] = true;
1237 for command_name, command in pairs(commands) do
1238 if not done[command_name] and not hidden_commands:contains(command_name) then
1239 command{ "--help" };
1241 done[command_name] = true;
1249 os.exit(commands[command]({ select(2, unpack(arg)) }));