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;
56 local dependencies = require "util.dependencies";
57 if not dependencies.check_dependencies() then
61 config = require "core.configmanager"
67 if arg[1] == "--config" and arg[2] then
68 table.insert(filenames, arg[2]);
69 table.remove(arg, 1); table.remove(arg, 1);
71 table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
74 for _, format in ipairs(config.parsers()) do
75 table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
78 for _,_filename in ipairs(filenames) do
80 local file = io.open(filename);
83 CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
87 local ok, level, err = config.load(filename);
90 print("**************************");
91 if level == "parser" then
92 print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
93 local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
94 print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
96 elseif level == "file" then
97 print("Prosody was unable to find the configuration file.");
98 print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
99 print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
100 print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
102 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
104 print("**************************");
109 local original_logging_config = config.get("*", "core", "log");
110 config.set("*", "core", "log", { { levels = { min="info" }, to = "console" } });
112 local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
113 local custom_plugin_paths = config.get("*", "core", "plugin_paths");
114 if custom_plugin_paths then
115 local path_sep = package.config:sub(3,3);
116 -- path1;path2;path3;defaultpath...
117 CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
119 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR,
120 plugins = CFG_PLUGINDIR or "plugins", data = data_path };
122 require "core.loggingmanager"
124 dependencies.log_warnings();
126 -- Switch away from root and into the prosody user --
127 local switched_user, current_uid;
129 local want_pposix_version = "0.3.5";
130 local ok, pposix = pcall(require, "util.pposix");
132 if ok and pposix then
133 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
134 current_uid = pposix.getuid();
135 if current_uid == 0 then
137 local desired_user = config.get("*", "core", "prosody_user") or "prosody";
138 local desired_group = config.get("*", "core", "prosody_group") or desired_user;
139 local ok, err = pposix.setgid(desired_group);
141 ok, err = pposix.initgroups(desired_user);
144 ok, err = pposix.setuid(desired_user);
147 switched_user = true;
150 if not switched_user then
152 print("Warning: Couldn't switch to Prosody user/group '"..tostring(desired_user).."'/'"..tostring(desired_group).."': "..tostring(err));
156 -- Set our umask to protect data files
157 pposix.umask(config.get("*", "core", "umask") or "027");
159 print("Error: Unable to load pposix module. Check that Prosody is installed correctly.")
160 print("For more help send the below error to us through http://prosody.im/discuss");
161 print(tostring(pposix))
164 local function test_writeable(filename)
165 local f, err = io.open(filename, "a");
173 local unwriteable_files = {};
174 if type(original_logging_config) == "string" and original_logging_config:sub(1,1) ~= "*" then
175 local ok, err = test_writeable(original_logging_config);
177 table.insert(unwriteable_files, err);
179 elseif type(original_logging_config) == "table" then
180 for _, rule in ipairs(original_logging_config) do
181 if rule.filename then
182 local ok, err = test_writeable(rule.filename);
184 table.insert(unwriteable_files, err);
190 if #unwriteable_files > 0 then
191 print("One of more of the Prosody log files are not");
192 print("writeable, please correct the errors and try");
193 print("starting prosodyctl again.");
195 for _, err in ipairs(unwriteable_files) do
203 local error_messages = setmetatable({
204 ["invalid-username"] = "The given username is invalid in a Jabber ID";
205 ["invalid-hostname"] = "The given hostname is invalid";
206 ["no-password"] = "No password was supplied";
207 ["no-such-user"] = "The given user does not exist on the server";
208 ["no-such-host"] = "The given hostname does not exist in the config";
209 ["unable-to-save-data"] = "Unable to store, perhaps you don't have permission?";
210 ["no-pidfile"] = "There is no 'pidfile' option in the configuration file, see http://prosody.im/doc/prosodyctl#pidfile for help";
211 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see http://prosody.im/doc/prosodyctl for more info";
212 ["no-such-method"] = "This module has no commands";
213 ["not-running"] = "Prosody is not running";
214 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
216 hosts = prosody.hosts;
218 local function make_host(hostname)
221 events = prosody.events,
222 users = require "core.usermanager".new_null_provider(hostname)
226 for hostname, config in pairs(config.getconfig()) do
227 hosts[hostname] = make_host(hostname);
230 require "core.modulemanager"
232 require "util.prosodyctl"
234 -----------------------
236 local show_message, show_warning = prosodyctl.show_message, prosodyctl.show_warning;
237 local show_usage = prosodyctl.show_usage;
238 local getchar, getpass = prosodyctl.getchar, prosodyctl.getpass;
239 local show_yesno = prosodyctl.show_yesno;
240 local show_prompt = prosodyctl.show_prompt;
241 local read_password = prosodyctl.read_password;
243 local prosodyctl_timeout = (config.get("*", "core", "prosodyctl_timeout") or 5) * 2;
244 -----------------------
246 local command = arg[1];
248 function commands.adduser(arg)
249 if not arg[1] or arg[1] == "--help" then
250 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
253 local user, host = arg[1]:match("([^@]+)@(.+)");
254 if not user and host then
255 show_message [[Failed to understand JID, please supply the JID you want to create]]
256 show_usage [[adduser user@host]]
261 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
265 if not hosts[host] then
266 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
267 show_warning("The user will not be able to log in until this is changed.");
268 hosts[host] = make_host(host);
271 if prosodyctl.user_exists{ user = user, host = host } then
272 show_message [[That user already exists]];
276 local password = read_password();
277 if not password then return 1; end
279 local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
281 if ok then return 0; end
287 function commands.passwd(arg)
288 if not arg[1] or arg[1] == "--help" then
289 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
292 local user, host = arg[1]:match("([^@]+)@(.+)");
293 if not user and host then
294 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
295 show_usage [[passwd user@host]]
300 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
304 if not hosts[host] then
305 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
306 show_warning("The user will not be able to log in until this is changed.");
307 hosts[host] = make_host(host);
310 if not prosodyctl.user_exists { user = user, host = host } then
311 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
315 local password = read_password();
316 if not password then return 1; end
318 local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
320 if ok then return 0; end
322 show_message(error_messages[msg])
326 function commands.deluser(arg)
327 if not arg[1] or arg[1] == "--help" then
328 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
331 local user, host = arg[1]:match("([^@]+)@(.+)");
332 if not user and host then
333 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
334 show_usage [[passwd user@host]]
339 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
343 if not hosts[host] then
344 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
345 show_warning("The user will not be able to log in until this is changed.");
346 hosts[host] = make_host(host);
349 if not prosodyctl.user_exists { user = user, host = host } then
350 show_message [[That user does not exist on this server]]
354 local ok, msg = prosodyctl.passwd { user = user, host = host };
356 if ok then return 0; end
358 show_message(error_messages[msg])
362 function commands.start(arg)
363 if arg[1] == "--help" then
364 show_usage([[start]], [[Start Prosody]]);
367 local ok, ret = prosodyctl.isrunning();
369 show_message(error_messages[ret]);
374 local ok, ret = prosodyctl.getpid();
376 show_message("Couldn't get running Prosody's PID");
377 show_message(error_messages[ret]);
380 show_message("Prosody is already running with PID %s", ret or "(unknown)");
384 local ok, ret = prosodyctl.start();
386 if config.get("*", "core", "daemonize") ~= false then
389 local ok, running = prosodyctl.isrunning();
390 if ok and running then
393 show_message("Still waiting...");
394 elseif i >= prosodyctl_timeout then
395 show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
401 show_message("Started");
406 show_message("Failed to start Prosody");
407 show_message(error_messages[ret])
411 function commands.status(arg)
412 if arg[1] == "--help" then
413 show_usage([[status]], [[Reports the running status of Prosody]]);
417 local ok, ret = prosodyctl.isrunning();
419 show_message(error_messages[ret]);
424 local ok, ret = prosodyctl.getpid();
426 show_message("Couldn't get running Prosody's PID");
427 show_message(error_messages[ret]);
430 show_message("Prosody is running with PID %s", ret or "(unknown)");
433 show_message("Prosody is not running");
434 if not switched_user and current_uid ~= 0 then
436 print(" You will also see this if prosodyctl is not running under");
437 print(" the same user account as Prosody. Try running as root (e.g. ");
438 print(" with 'sudo' in front) to gain access to Prosody's real status.");
445 function commands.stop(arg)
446 if arg[1] == "--help" then
447 show_usage([[stop]], [[Stop a running Prosody server]]);
451 if not prosodyctl.isrunning() then
452 show_message("Prosody is not running");
456 local ok, ret = prosodyctl.stop();
460 local ok, running = prosodyctl.isrunning();
461 if ok and not running then
464 show_message("Still waiting...");
465 elseif i >= prosodyctl_timeout then
466 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
472 show_message("Stopped");
476 show_message(error_messages[ret]);
480 function commands.restart(arg)
481 if arg[1] == "--help" then
482 show_usage([[restart]], [[Restart a running Prosody server]]);
487 return commands.start(arg);
490 function commands.about(arg)
491 if arg[1] == "--help" then
492 show_usage([[about]], [[Show information about this Prosody installation]]);
496 require "util.array";
497 local keys = require "util.iterators".keys;
499 print("Prosody "..(prosody.version or "(unknown version)"));
501 print("# Prosody directories");
502 print("Data directory: ", CFG_DATADIR or "./");
503 print("Plugin directory:", CFG_PLUGINDIR or "./");
504 print("Config directory:", CFG_CONFIGDIR or "./");
505 print("Source directory:", CFG_SOURCEDIR or "./");
507 print("# Lua environment");
508 print("Lua version: ", _G._VERSION);
510 print("Lua module search paths:");
511 for path in package.path:gmatch("[^;]+") do
515 print("Lua C module search paths:");
516 for path in package.cpath:gmatch("[^;]+") do
520 local luarocks_status = (pcall(require, "luarocks.loader") and "Installed ("..(luarocks.cfg.program_version or "2.x+")..")")
521 or (pcall(require, "luarocks.require") and "Installed (1.x)")
523 print("LuaRocks: ", luarocks_status);
525 print("# Lua module versions");
526 local module_versions, longest_name = {}, 8;
527 for name, module in pairs(package.loaded) do
528 if type(module) == "table" and rawget(module, "_VERSION")
529 and name ~= "_G" and not name:match("%.") then
530 if #name > longest_name then
531 longest_name = #name;
533 module_versions[name] = module._VERSION;
536 local sorted_keys = array.collect(keys(module_versions)):sort();
537 for _, name in ipairs(array.collect(keys(module_versions)):sort()) do
538 print(name..":"..string.rep(" ", longest_name-#name), module_versions[name]);
543 function commands.reload(arg)
544 if arg[1] == "--help" then
545 show_usage([[reload]], [[Reload Prosody's configuration and re-open log files]]);
549 if not prosodyctl.isrunning() then
550 show_message("Prosody is not running");
554 local ok, ret = prosodyctl.reload();
557 show_message("Prosody log files re-opened and config file reloaded. You may need to reload modules for some changes to take effect.");
561 show_message(error_messages[ret]);
564 -- ejabberdctl compatibility
566 function commands.register(arg)
567 local user, host, password = unpack(arg);
568 if (not (user and host)) or arg[1] == "--help" then
569 if user ~= "--help" then
571 show_message [[No username specified]]
573 show_message [[Please specify which host you want to register the user on]];
576 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
580 password = read_password();
582 show_message [[Unable to register user with no password]];
587 local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
589 if ok then return 0; end
591 show_message(error_messages[msg])
595 function commands.unregister(arg)
596 local user, host = 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 unregister the user from]];
605 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
609 local ok, msg = prosodyctl.deluser { user = user, host = host };
611 if ok then return 0; end
613 show_message(error_messages[msg])
617 local openssl = require "util.openssl";
618 local lfs = require "lfs";
620 local cert_commands = {};
622 local function ask_overwrite(filename)
623 return lfs.attributes(filename) and not show_yesno("Overwrite "..filename .. "?");
626 function cert_commands.config(arg)
627 if #arg >= 1 and arg[1] ~= "--help" then
628 local conf_filename = (CFG_DATADIR or ".") .. "/" .. arg[1] .. ".cnf";
629 if ask_overwrite(conf_filename) then
630 return nil, conf_filename;
632 local conf = openssl.config.new();
633 conf:from_prosody(hosts, config, arg);
634 for k, v in pairs(conf.distinguished_name) do
636 if k == "commonName" then
638 elseif k == "emailAddress" then
639 v = "xmpp@" .. arg[1];
641 nv = show_prompt(("%s (%s):"):format(k, nv or v));
642 nv = (not nv or nv == "") and v or nv;
643 conf.distinguished_name[k] = nv ~= "." and nv or nil;
645 local conf_file = io.open(conf_filename, "w");
646 conf_file:write(conf:serialize());
649 show_message("Config written to " .. conf_filename);
650 return nil, conf_filename;
652 show_usage("cert config HOSTNAME [HOSTNAME+]", "Builds a certificate config file covering the supplied hostname(s)")
656 function cert_commands.key(arg)
657 if #arg >= 1 and arg[1] ~= "--help" then
658 local key_filename = (CFG_DATADIR or ".") .. "/" .. arg[1] .. ".key";
659 if ask_overwrite(key_filename) then
660 return nil, key_filename;
662 os.remove(key_filename); -- We chmod this file to not have write permissions
663 local key_size = tonumber(arg[2] or show_prompt("Choose key size (2048):") or 2048);
664 if openssl.genrsa{out=key_filename, key_size} then
665 os.execute(("chmod 400 '%s'"):format(key_filename));
666 show_message("Key written to ".. key_filename);
667 return nil, key_filename;
669 show_message("There was a problem, see OpenSSL output");
671 show_usage("cert key HOSTNAME <bits>", "Generates a RSA key named HOSTNAME.key\n "
672 .."Promps for a key size if none given")
676 function cert_commands.request(arg)
677 if #arg >= 1 and arg[1] ~= "--help" then
678 local req_filename = (CFG_DATADIR or ".") .. "/" .. arg[1] .. ".req";
679 if ask_overwrite(req_filename) then
680 return nil, req_filename;
682 local _, key_filename = cert_commands.key({arg[1]});
683 local _, conf_filename = cert_commands.config(arg);
684 if openssl.req{new=true, key=key_filename, utf8=true, config=conf_filename, out=req_filename} then
685 show_message("Certificate request written to ".. req_filename);
687 show_message("There was a problem, see OpenSSL output");
690 show_usage("cert request HOSTNAME [HOSTNAME+]", "Generates a certificate request for the supplied hostname(s)")
694 function cert_commands.generate(arg)
695 if #arg >= 1 and arg[1] ~= "--help" then
696 local cert_filename = (CFG_DATADIR or ".") .. "/" .. arg[1] .. ".cert";
697 if ask_overwrite(cert_filename) then
698 return nil, conf_filename;
700 local _, key_filename = cert_commands.key({arg[1]});
701 local _, conf_filename = cert_commands.config(arg);
703 if key_filename and conf_filename and cert_filename
704 and openssl.req{new=true, x509=true, nodes=true, key=key_filename,
705 days=365, sha1=true, utf8=true, config=conf_filename, out=cert_filename} then
706 show_message("Certificate written to ".. cert_filename);
708 show_message("There was a problem, see OpenSSL output");
711 show_usage("cert generate HOSTNAME [HOSTNAME+]", "Generates a self-signed certificate for the current hostname(s)")
715 function commands.cert(arg)
716 if #arg >= 1 and arg[1] ~= "--help" then
717 local subcmd = table.remove(arg, 1);
718 if type(cert_commands[subcmd]) == "function" then
720 show_message"You need to supply at least one hostname"
723 if arg[1] ~= "--help" and not hosts[arg[1]] then
724 show_message(error_messages["no-such-host"]);
727 return cert_commands[subcmd](arg);
730 show_usage("cert config|request|generate|key", "Helpers for generating X.509 certificates and keys.")
733 ---------------------
735 if command and command:match("^mod_") then -- Is a command in a module
736 local module_name = command:match("^mod_(.+)");
737 local ret, err = modulemanager.load("*", module_name);
739 show_message("Failed to load module '"..module_name.."': "..err);
743 table.remove(arg, 1);
745 local module = modulemanager.get_module("*", module_name);
747 show_message("Failed to load module '"..module_name.."': Unknown error");
751 if not modulemanager.module_has_method(module, "command") then
752 show_message("Fail: mod_"..module_name.." does not support any commands");
756 local ok, ret = modulemanager.call_module_method(module, "command", arg);
758 if type(ret) == "number" then
760 elseif type(ret) == "string" then
765 show_message("Failed to execute command: "..error_messages[ret]);
770 if not commands[command] then -- Show help for all commands
771 function show_usage(usage, desc)
776 print("prosodyctl - Manage a Prosody server");
778 print("Usage: "..arg[0].." COMMAND [OPTIONS]");
780 print("Where COMMAND may be one of:\n");
782 local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
783 local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart", "reload", "about" };
787 for _, command_name in ipairs(commands_order) do
788 local command = commands[command_name];
792 done[command_name] = true;
796 for command_name, command in pairs(commands) do
797 if not done[command_name] and not hidden_commands:contains(command_name) then
800 done[command_name] = true;
808 os.exit(commands[command]({ select(2, unpack(arg)) }));