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 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see http://prosody.im/doc/prosodyctl for more info";
224 ["no-such-method"] = "This module has no commands";
225 ["not-running"] = "Prosody is not running";
226 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
228 hosts = prosody.hosts;
230 local function make_host(hostname)
233 events = prosody.events,
235 users = require "core.usermanager".new_null_provider(hostname)
239 for hostname, config in pairs(config.getconfig()) do
240 hosts[hostname] = make_host(hostname);
243 local modulemanager = require "core.modulemanager"
245 local prosodyctl = require "util.prosodyctl"
247 -----------------------
249 -- FIXME: Duplicate code waiting for util.startup
250 function read_version()
251 -- Try to determine version
252 local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
254 prosody.version = version_file:read("*a"):gsub("%s*$", "");
255 version_file:close();
256 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
257 prosody.version = "hg:"..prosody.version;
260 prosody.version = "unknown";
264 local show_message, show_warning = prosodyctl.show_message, prosodyctl.show_warning;
265 local show_usage = prosodyctl.show_usage;
266 local getchar, getpass = prosodyctl.getchar, prosodyctl.getpass;
267 local show_yesno = prosodyctl.show_yesno;
268 local show_prompt = prosodyctl.show_prompt;
269 local read_password = prosodyctl.read_password;
271 local prosodyctl_timeout = (config.get("*", "prosodyctl_timeout") or 5) * 2;
272 -----------------------
274 local command = arg[1];
276 function commands.adduser(arg)
277 if not arg[1] or arg[1] == "--help" then
278 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
281 local user, host = arg[1]:match("([^@]+)@(.+)");
282 if not user and host then
283 show_message [[Failed to understand JID, please supply the JID you want to create]]
284 show_usage [[adduser user@host]]
289 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
293 if not hosts[host] then
294 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
295 show_warning("The user will not be able to log in until this is changed.");
296 hosts[host] = make_host(host);
299 if prosodyctl.user_exists{ user = user, host = host } then
300 show_message [[That user already exists]];
304 local password = read_password();
305 if not password then return 1; end
307 local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
309 if ok then return 0; end
315 function commands.passwd(arg)
316 if not arg[1] or arg[1] == "--help" then
317 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
320 local user, host = arg[1]:match("([^@]+)@(.+)");
321 if not user and host then
322 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
323 show_usage [[passwd user@host]]
328 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
332 if not hosts[host] then
333 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
334 show_warning("The user will not be able to log in until this is changed.");
335 hosts[host] = make_host(host);
338 if not prosodyctl.user_exists { user = user, host = host } then
339 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
343 local password = read_password();
344 if not password then return 1; end
346 local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
348 if ok then return 0; end
350 show_message(error_messages[msg])
354 function commands.deluser(arg)
355 if not arg[1] or arg[1] == "--help" then
356 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
359 local user, host = arg[1]:match("([^@]+)@(.+)");
360 if not user and host then
361 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
362 show_usage [[passwd user@host]]
367 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
371 if not hosts[host] then
372 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
373 show_warning("The user will not be able to log in until this is changed.");
374 hosts[host] = make_host(host);
377 if not prosodyctl.user_exists { user = user, host = host } then
378 show_message [[That user does not exist on this server]]
382 local ok, msg = prosodyctl.deluser { user = user, host = host };
384 if ok then return 0; end
386 show_message(error_messages[msg])
390 function commands.start(arg)
391 if arg[1] == "--help" then
392 show_usage([[start]], [[Start Prosody]]);
395 local ok, ret = prosodyctl.isrunning();
397 show_message(error_messages[ret]);
402 local ok, ret = prosodyctl.getpid();
404 show_message("Couldn't get running Prosody's PID");
405 show_message(error_messages[ret]);
408 show_message("Prosody is already running with PID %s", ret or "(unknown)");
412 local ok, ret = prosodyctl.start();
414 if config.get("*", "daemonize") ~= false then
417 local ok, running = prosodyctl.isrunning();
418 if ok and running then
421 show_message("Still waiting...");
422 elseif i >= prosodyctl_timeout then
423 show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
429 show_message("Started");
434 show_message("Failed to start Prosody");
435 show_message(error_messages[ret])
439 function commands.status(arg)
440 if arg[1] == "--help" then
441 show_usage([[status]], [[Reports the running status of Prosody]]);
445 local ok, ret = prosodyctl.isrunning();
447 show_message(error_messages[ret]);
452 local ok, ret = prosodyctl.getpid();
454 show_message("Couldn't get running Prosody's PID");
455 show_message(error_messages[ret]);
458 show_message("Prosody is running with PID %s", ret or "(unknown)");
461 show_message("Prosody is not running");
462 if not switched_user and current_uid ~= 0 then
464 print(" You will also see this if prosodyctl is not running under");
465 print(" the same user account as Prosody. Try running as root (e.g. ");
466 print(" with 'sudo' in front) to gain access to Prosody's real status.");
473 function commands.stop(arg)
474 if arg[1] == "--help" then
475 show_usage([[stop]], [[Stop a running Prosody server]]);
479 if not prosodyctl.isrunning() then
480 show_message("Prosody is not running");
484 local ok, ret = prosodyctl.stop();
488 local ok, running = prosodyctl.isrunning();
489 if ok and not running then
492 show_message("Still waiting...");
493 elseif i >= prosodyctl_timeout then
494 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
500 show_message("Stopped");
504 show_message(error_messages[ret]);
508 function commands.restart(arg)
509 if arg[1] == "--help" then
510 show_usage([[restart]], [[Restart a running Prosody server]]);
515 return commands.start(arg);
518 function commands.about(arg)
520 if arg[1] == "--help" then
521 show_usage([[about]], [[Show information about this Prosody installation]]);
525 local array = require "util.array";
526 local keys = require "util.iterators".keys;
528 print("Prosody "..(prosody.version or "(unknown version)"));
530 print("# Prosody directories");
531 print("Data directory: ", CFG_DATADIR or "./");
532 print("Plugin directory:", CFG_PLUGINDIR or "./");
533 print("Config directory:", CFG_CONFIGDIR or "./");
534 print("Source directory:", CFG_SOURCEDIR or "./");
536 print("# Lua environment");
537 print("Lua version: ", _G._VERSION);
539 print("Lua module search paths:");
540 for path in package.path:gmatch("[^;]+") do
544 print("Lua C module search paths:");
545 for path in package.cpath:gmatch("[^;]+") do
549 local luarocks_status = (pcall(require, "luarocks.loader") and "Installed ("..(luarocks.cfg.program_version or "2.x+")..")")
550 or (pcall(require, "luarocks.require") and "Installed (1.x)")
552 print("LuaRocks: ", luarocks_status);
554 print("# Lua module versions");
555 local module_versions, longest_name = {}, 8;
556 for name, module in pairs(package.loaded) do
557 if type(module) == "table" and rawget(module, "_VERSION")
558 and name ~= "_G" and not name:match("%.") then
559 if #name > longest_name then
560 longest_name = #name;
562 module_versions[name] = module._VERSION;
565 local sorted_keys = array.collect(keys(module_versions)):sort();
566 for _, name in ipairs(array.collect(keys(module_versions)):sort()) do
567 print(name..":"..string.rep(" ", longest_name-#name), module_versions[name]);
572 function commands.reload(arg)
573 if arg[1] == "--help" then
574 show_usage([[reload]], [[Reload Prosody's configuration and re-open log files]]);
578 if not prosodyctl.isrunning() then
579 show_message("Prosody is not running");
583 local ok, ret = prosodyctl.reload();
586 show_message("Prosody log files re-opened and config file reloaded. You may need to reload modules for some changes to take effect.");
590 show_message(error_messages[ret]);
593 -- ejabberdctl compatibility
595 function commands.register(arg)
596 local user, host, password = unpack(arg);
597 if (not (user and host)) or arg[1] == "--help" then
598 if user ~= "--help" then
600 show_message [[No username specified]]
602 show_message [[Please specify which host you want to register the user on]];
605 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
609 password = read_password();
611 show_message [[Unable to register user with no password]];
616 local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
618 if ok then return 0; end
620 show_message(error_messages[msg])
624 function commands.unregister(arg)
625 local user, host = unpack(arg);
626 if (not (user and host)) or arg[1] == "--help" then
627 if user ~= "--help" then
629 show_message [[No username specified]]
631 show_message [[Please specify which host you want to unregister the user from]];
634 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
638 local ok, msg = prosodyctl.deluser { user = user, host = host };
640 if ok then return 0; end
642 show_message(error_messages[msg])
649 local cert_commands = {};
651 local function ask_overwrite(filename)
652 return lfs.attributes(filename) and not show_yesno("Overwrite "..filename .. "?");
655 function cert_commands.config(arg)
656 if #arg >= 1 and arg[1] ~= "--help" then
657 local conf_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".cnf";
658 if ask_overwrite(conf_filename) then
659 return nil, conf_filename;
661 local conf = openssl.config.new();
662 conf:from_prosody(hosts, config, arg);
663 show_message("Please provide details to include in the certificate config file.");
664 show_message("Leave the field empty to use the default value or '.' to exclude the field.")
665 for i, k in ipairs(openssl._DN_order) do
666 local v = conf.distinguished_name[k];
669 if k == "commonName" then
671 elseif k == "emailAddress" then
672 v = "xmpp@" .. arg[1];
673 elseif k == "countryName" then
674 local tld = arg[1]:match"%.([a-z]+)$";
675 if tld and #tld == 2 and tld ~= "uk" then
679 nv = show_prompt(("%s (%s):"):format(k, nv or v));
680 nv = (not nv or nv == "") and v or nv;
681 if nv:find"[\192-\252][\128-\191]+" then
682 conf.req.string_mask = "utf8only"
684 conf.distinguished_name[k] = nv ~= "." and nv or nil;
687 local conf_file = io.open(conf_filename, "w");
688 conf_file:write(conf:serialize());
691 show_message("Config written to " .. conf_filename);
692 return nil, conf_filename;
694 show_usage("cert config HOSTNAME [HOSTNAME+]", "Builds a certificate config file covering the supplied hostname(s)")
698 function cert_commands.key(arg)
699 if #arg >= 1 and arg[1] ~= "--help" then
700 local key_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".key";
701 if ask_overwrite(key_filename) then
702 return nil, key_filename;
704 os.remove(key_filename); -- This file, if it exists is unlikely to have write permissions
705 local key_size = tonumber(arg[2] or show_prompt("Choose key size (2048):") or 2048);
706 local old_umask = pposix.umask("0377");
707 if openssl.genrsa{out=key_filename, key_size} then
708 os.execute(("chmod 400 '%s'"):format(key_filename));
709 show_message("Key written to ".. key_filename);
710 pposix.umask(old_umask);
711 return nil, key_filename;
713 show_message("There was a problem, see OpenSSL output");
715 show_usage("cert key HOSTNAME <bits>", "Generates a RSA key named HOSTNAME.key\n "
716 .."Prompts for a key size if none given")
720 function cert_commands.request(arg)
721 if #arg >= 1 and arg[1] ~= "--help" then
722 local req_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".req";
723 if ask_overwrite(req_filename) then
724 return nil, req_filename;
726 local _, key_filename = cert_commands.key({arg[1]});
727 local _, conf_filename = cert_commands.config(arg);
728 if openssl.req{new=true, key=key_filename, utf8=true, config=conf_filename, out=req_filename} then
729 show_message("Certificate request written to ".. req_filename);
731 show_message("There was a problem, see OpenSSL output");
734 show_usage("cert request HOSTNAME [HOSTNAME+]", "Generates a certificate request for the supplied hostname(s)")
738 function cert_commands.generate(arg)
739 if #arg >= 1 and arg[1] ~= "--help" then
740 local cert_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".crt";
741 if ask_overwrite(cert_filename) then
742 return nil, cert_filename;
744 local _, key_filename = cert_commands.key({arg[1]});
745 local _, conf_filename = cert_commands.config(arg);
747 if key_filename and conf_filename and cert_filename
748 and openssl.req{new=true, x509=true, nodes=true, key=key_filename,
749 days=365, sha1=true, utf8=true, config=conf_filename, out=cert_filename} then
750 show_message("Certificate written to ".. cert_filename);
752 show_message("There was a problem, see OpenSSL output");
755 show_usage("cert generate HOSTNAME [HOSTNAME+]", "Generates a self-signed certificate for the current hostname(s)")
759 function commands.cert(arg)
760 if #arg >= 1 and arg[1] ~= "--help" then
761 openssl = require "util.openssl";
763 local subcmd = table.remove(arg, 1);
764 if type(cert_commands[subcmd]) == "function" then
766 show_message"You need to supply at least one hostname"
769 if arg[1] ~= "--help" and not hosts[arg[1]] then
770 show_message(error_messages["no-such-host"]);
773 return cert_commands[subcmd](arg);
776 show_usage("cert config|request|generate|key", "Helpers for generating X.509 certificates and keys.")
779 ---------------------
781 if command and command:match("^mod_") then -- Is a command in a module
782 local module_name = command:match("^mod_(.+)");
783 local ret, err = modulemanager.load("*", module_name);
785 show_message("Failed to load module '"..module_name.."': "..err);
789 table.remove(arg, 1);
791 local module = modulemanager.get_module("*", module_name);
793 show_message("Failed to load module '"..module_name.."': Unknown error");
797 if not modulemanager.module_has_method(module, "command") then
798 show_message("Fail: mod_"..module_name.." does not support any commands");
802 local ok, ret = modulemanager.call_module_method(module, "command", arg);
804 if type(ret) == "number" then
806 elseif type(ret) == "string" then
811 show_message("Failed to execute command: "..error_messages[ret]);
816 if not commands[command] then -- Show help for all commands
817 function show_usage(usage, desc)
822 print("prosodyctl - Manage a Prosody server");
824 print("Usage: "..arg[0].." COMMAND [OPTIONS]");
826 print("Where COMMAND may be one of:\n");
828 local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
829 local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart", "reload", "about" };
833 for _, command_name in ipairs(commands_order) do
834 local command = commands[command_name];
838 done[command_name] = true;
842 for command_name, command in pairs(commands) do
843 if not done[command_name] and not hidden_commands:contains(command_name) then
846 done[command_name] = true;
854 os.exit(commands[command]({ select(2, unpack(arg)) }));