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 require "core.loggingmanager"
114 dependencies.log_warnings();
116 local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
117 require "util.datamanager".set_data_path(data_path);
119 -- Switch away from root and into the prosody user --
120 local switched_user, current_uid;
122 local want_pposix_version = "0.3.5";
123 local ok, pposix = pcall(require, "util.pposix");
125 if ok and pposix then
126 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
127 current_uid = pposix.getuid();
128 if current_uid == 0 then
130 local desired_user = config.get("*", "core", "prosody_user") or "prosody";
131 local desired_group = config.get("*", "core", "prosody_group") or desired_user;
132 local ok, err = pposix.setgid(desired_group);
134 ok, err = pposix.initgroups(desired_user);
137 ok, err = pposix.setuid(desired_user);
140 switched_user = true;
143 if not switched_user then
145 print("Warning: Couldn't switch to Prosody user/group '"..tostring(desired_user).."'/'"..tostring(desired_group).."': "..tostring(err));
149 -- Set our umask to protect data files
150 pposix.umask(config.get("*", "core", "umask") or "027");
152 print("Error: Unable to load pposix module. Check that Prosody is installed correctly.")
153 print("For more help send the below error to us through http://prosody.im/discuss");
154 print(tostring(pposix))
157 local function test_writeable(filename)
158 local f, err = io.open(filename, "a");
166 local unwriteable_files = {};
167 if type(original_logging_config) == "string" and original_logging_config:sub(1,1) ~= "*" then
168 local ok, err = test_writeable(original_logging_config);
170 table.insert(unwriteable_files, err);
172 elseif type(original_logging_config) == "table" then
173 for _, rule in ipairs(original_logging_config) do
174 if rule.filename then
175 local ok, err = test_writeable(rule.filename);
177 table.insert(unwriteable_files, err);
183 if #unwriteable_files > 0 then
184 print("One of more of the Prosody log files are not");
185 print("writeable, please correct the errors and try");
186 print("starting prosodyctl again.");
188 for _, err in ipairs(unwriteable_files) do
196 local error_messages = setmetatable({
197 ["invalid-username"] = "The given username is invalid in a Jabber ID";
198 ["invalid-hostname"] = "The given hostname is invalid";
199 ["no-password"] = "No password was supplied";
200 ["no-such-user"] = "The given user does not exist on the server";
201 ["unable-to-save-data"] = "Unable to store, perhaps you don't have permission?";
202 ["no-pidfile"] = "There is no 'pidfile' option in the configuration file, see http://prosody.im/doc/prosodyctl#pidfile for help";
203 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see http://prosody.im/doc/prosodyctl for more info";
204 ["no-such-method"] = "This module has no commands";
205 ["not-running"] = "Prosody is not running";
206 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
208 hosts = prosody.hosts;
210 local function make_host(hostname)
213 events = prosody.events,
214 users = require "core.usermanager".new_null_provider(hostname)
218 for hostname, config in pairs(config.getconfig()) do
219 hosts[hostname] = make_host(hostname);
222 require "core.modulemanager"
224 require "util.prosodyctl"
226 -----------------------
228 function show_message(msg, ...)
229 print(msg:format(...));
232 function show_warning(msg, ...)
233 print(msg:format(...));
236 function show_usage(usage, desc)
237 print("Usage: "..arg[0].." "..usage);
243 local function getchar(n)
244 local stty_ret = os.execute("stty raw -echo 2>/dev/null");
246 if stty_ret == 0 then
247 ok, char = pcall(io.read, n or 1);
248 os.execute("stty sane");
250 ok, char = pcall(io.read, "*l");
252 char = char:sub(1, n or 1);
260 local function getpass()
261 local stty_ret = os.execute("stty -echo 2>/dev/null");
262 if stty_ret ~= 0 then
263 io.write("\027[08m"); -- ANSI 'hidden' text attribute
265 local ok, pass = pcall(io.read, "*l");
266 if stty_ret == 0 then
267 os.execute("stty sane");
269 io.write("\027[00m");
277 function show_yesno(prompt)
278 io.write(prompt, " ");
279 local choice = getchar():lower();
281 if not choice:match("%a") then
282 choice = prompt:match("%[.-(%U).-%]$");
283 if not choice then return nil; end
285 return (choice == "y");
288 local function read_password()
291 io.write("Enter new password: ");
292 password = getpass();
294 show_message("No password - cancelled");
297 io.write("Retype new password: ");
298 if getpass() ~= password then
299 if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then
309 local prosodyctl_timeout = (config.get("*", "core", "prosodyctl_timeout") or 5) * 2;
310 -----------------------
312 local command = arg[1];
314 function commands.adduser(arg)
315 if not arg[1] or arg[1] == "--help" then
316 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
319 local user, host = arg[1]:match("([^@]+)@(.+)");
320 if not user and host then
321 show_message [[Failed to understand JID, please supply the JID you want to create]]
322 show_usage [[adduser user@host]]
327 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
331 if not hosts[host] then
332 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
333 show_warning("The user will not be able to log in until this is changed.");
334 hosts[host] = make_host(host);
337 if prosodyctl.user_exists{ user = user, host = host } then
338 show_message [[That user already exists]];
342 local password = read_password();
343 if not password then return 1; end
345 local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
347 if ok then return 0; end
353 function commands.passwd(arg)
354 if not arg[1] or arg[1] == "--help" then
355 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
358 local user, host = arg[1]:match("([^@]+)@(.+)");
359 if not user and host then
360 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
361 show_usage [[passwd user@host]]
366 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
370 if not hosts[host] then
371 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
372 show_warning("The user will not be able to log in until this is changed.");
373 hosts[host] = make_host(host);
376 if not prosodyctl.user_exists { user = user, host = host } then
377 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
381 local password = read_password();
382 if not password then return 1; end
384 local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
386 if ok then return 0; end
388 show_message(error_messages[msg])
392 function commands.deluser(arg)
393 if not arg[1] or arg[1] == "--help" then
394 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
397 local user, host = arg[1]:match("([^@]+)@(.+)");
398 if not user and host then
399 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
400 show_usage [[passwd user@host]]
405 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
409 if not hosts[host] then
410 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
411 show_warning("The user will not be able to log in until this is changed.");
412 hosts[host] = make_host(host);
415 if not prosodyctl.user_exists { user = user, host = host } then
416 show_message [[That user does not exist on this server]]
420 local ok, msg = prosodyctl.passwd { user = user, host = host };
422 if ok then return 0; end
424 show_message(error_messages[msg])
428 function commands.start(arg)
429 if arg[1] == "--help" then
430 show_usage([[start]], [[Start Prosody]]);
433 local ok, ret = prosodyctl.isrunning();
435 show_message(error_messages[ret]);
440 local ok, ret = prosodyctl.getpid();
442 show_message("Couldn't get running Prosody's PID");
443 show_message(error_messages[ret]);
446 show_message("Prosody is already running with PID %s", ret or "(unknown)");
450 local ok, ret = prosodyctl.start();
452 if config.get("*", "core", "daemonize") ~= false then
455 local ok, running = prosodyctl.isrunning();
456 if ok and running then
459 show_message("Still waiting...");
460 elseif i >= prosodyctl_timeout then
461 show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
467 show_message("Started");
472 show_message("Failed to start Prosody");
473 show_message(error_messages[ret])
477 function commands.status(arg)
478 if arg[1] == "--help" then
479 show_usage([[status]], [[Reports the running status of Prosody]]);
483 local ok, ret = prosodyctl.isrunning();
485 show_message(error_messages[ret]);
490 local ok, ret = prosodyctl.getpid();
492 show_message("Couldn't get running Prosody's PID");
493 show_message(error_messages[ret]);
496 show_message("Prosody is running with PID %s", ret or "(unknown)");
499 show_message("Prosody is not running");
500 if not switched_user and current_uid ~= 0 then
502 print(" You will also see this if prosodyctl is not running under");
503 print(" the same user account as Prosody. Try running as root (e.g. ");
504 print(" with 'sudo' in front) to gain access to Prosody's real status.");
511 function commands.stop(arg)
512 if arg[1] == "--help" then
513 show_usage([[stop]], [[Stop a running Prosody server]]);
517 if not prosodyctl.isrunning() then
518 show_message("Prosody is not running");
522 local ok, ret = prosodyctl.stop();
526 local ok, running = prosodyctl.isrunning();
527 if ok and not running then
530 show_message("Still waiting...");
531 elseif i >= prosodyctl_timeout then
532 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
538 show_message("Stopped");
542 show_message(error_messages[ret]);
546 function commands.restart(arg)
547 if arg[1] == "--help" then
548 show_usage([[restart]], [[Restart a running Prosody server]]);
553 return commands.start(arg);
556 -- ejabberdctl compatibility
558 function commands.register(arg)
559 local user, host, password = unpack(arg);
560 if (not (user and host)) or arg[1] == "--help" then
561 if user ~= "--help" then
563 show_message [[No username specified]]
565 show_message [[Please specify which host you want to register the user on]];
568 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
572 password = read_password();
574 show_message [[Unable to register user with no password]];
579 local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
581 if ok then return 0; end
583 show_message(error_messages[msg])
587 function commands.unregister(arg)
588 local user, host = unpack(arg);
589 if (not (user and host)) or arg[1] == "--help" then
590 if user ~= "--help" then
592 show_message [[No username specified]]
594 show_message [[Please specify which host you want to unregister the user from]];
597 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
601 local ok, msg = prosodyctl.deluser { user = user, host = host };
603 if ok then return 0; end
605 show_message(error_messages[msg])
609 ---------------------
611 if command and command:match("^mod_") then -- Is a command in a module
612 local module_name = command:match("^mod_(.+)");
613 local ret, err = modulemanager.load("*", module_name);
615 show_message("Failed to load module '"..module_name.."': "..err);
619 table.remove(arg, 1);
621 local module = modulemanager.get_module("*", module_name);
623 show_message("Failed to load module '"..module_name.."': Unknown error");
627 if not modulemanager.module_has_method(module, "command") then
628 show_message("Fail: mod_"..module_name.." does not support any commands");
632 local ok, ret = modulemanager.call_module_method(module, "command", arg);
634 if type(ret) == "number" then
636 elseif type(ret) == "string" then
641 show_message("Failed to execute command: "..error_messages[ret]);
646 if not commands[command] then -- Show help for all commands
647 function show_usage(usage, desc)
652 print("prosodyctl - Manage a Prosody server");
654 print("Usage: "..arg[0].." COMMAND [OPTIONS]");
656 print("Where COMMAND may be one of:\n");
658 local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
659 local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart" };
663 for _, command_name in ipairs(commands_order) do
664 local command = commands[command_name];
668 done[command_name] = true;
672 for command_name, command in pairs(commands) do
673 if not done[command_name] and not hidden_commands:contains(command_name) then
676 done[command_name] = true;
684 os.exit(commands[command]({ select(2, unpack(arg)) }));