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 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR,
114 plugins = CFG_PLUGINDIR, data = data_path };
116 require "core.loggingmanager"
118 dependencies.log_warnings();
120 -- Switch away from root and into the prosody user --
121 local switched_user, current_uid;
123 local want_pposix_version = "0.3.5";
124 local ok, pposix = pcall(require, "util.pposix");
126 if ok and pposix then
127 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
128 current_uid = pposix.getuid();
129 if current_uid == 0 then
131 local desired_user = config.get("*", "core", "prosody_user") or "prosody";
132 local desired_group = config.get("*", "core", "prosody_group") or desired_user;
133 local ok, err = pposix.setgid(desired_group);
135 ok, err = pposix.initgroups(desired_user);
138 ok, err = pposix.setuid(desired_user);
141 switched_user = true;
144 if not switched_user then
146 print("Warning: Couldn't switch to Prosody user/group '"..tostring(desired_user).."'/'"..tostring(desired_group).."': "..tostring(err));
150 -- Set our umask to protect data files
151 pposix.umask(config.get("*", "core", "umask") or "027");
153 print("Error: Unable to load pposix module. Check that Prosody is installed correctly.")
154 print("For more help send the below error to us through http://prosody.im/discuss");
155 print(tostring(pposix))
158 local function test_writeable(filename)
159 local f, err = io.open(filename, "a");
167 local unwriteable_files = {};
168 if type(original_logging_config) == "string" and original_logging_config:sub(1,1) ~= "*" then
169 local ok, err = test_writeable(original_logging_config);
171 table.insert(unwriteable_files, err);
173 elseif type(original_logging_config) == "table" then
174 for _, rule in ipairs(original_logging_config) do
175 if rule.filename then
176 local ok, err = test_writeable(rule.filename);
178 table.insert(unwriteable_files, err);
184 if #unwriteable_files > 0 then
185 print("One of more of the Prosody log files are not");
186 print("writeable, please correct the errors and try");
187 print("starting prosodyctl again.");
189 for _, err in ipairs(unwriteable_files) do
197 local error_messages = setmetatable({
198 ["invalid-username"] = "The given username is invalid in a Jabber ID";
199 ["invalid-hostname"] = "The given hostname is invalid";
200 ["no-password"] = "No password was supplied";
201 ["no-such-user"] = "The given user does not exist on the server";
202 ["unable-to-save-data"] = "Unable to store, perhaps you don't have permission?";
203 ["no-pidfile"] = "There is no 'pidfile' option in the configuration file, see http://prosody.im/doc/prosodyctl#pidfile for help";
204 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see http://prosody.im/doc/prosodyctl for more info";
205 ["no-such-method"] = "This module has no commands";
206 ["not-running"] = "Prosody is not running";
207 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
209 hosts = prosody.hosts;
211 local function make_host(hostname)
214 events = prosody.events,
215 users = require "core.usermanager".new_null_provider(hostname)
219 for hostname, config in pairs(config.getconfig()) do
220 hosts[hostname] = make_host(hostname);
223 require "core.modulemanager"
225 require "util.prosodyctl"
227 -----------------------
229 function show_message(msg, ...)
230 print(msg:format(...));
233 function show_warning(msg, ...)
234 print(msg:format(...));
237 function show_usage(usage, desc)
238 print("Usage: "..arg[0].." "..usage);
244 local function getchar(n)
245 local stty_ret = os.execute("stty raw -echo 2>/dev/null");
247 if stty_ret == 0 then
248 ok, char = pcall(io.read, n or 1);
249 os.execute("stty sane");
251 ok, char = pcall(io.read, "*l");
253 char = char:sub(1, n or 1);
261 local function getpass()
262 local stty_ret = os.execute("stty -echo 2>/dev/null");
263 if stty_ret ~= 0 then
264 io.write("\027[08m"); -- ANSI 'hidden' text attribute
266 local ok, pass = pcall(io.read, "*l");
267 if stty_ret == 0 then
268 os.execute("stty sane");
270 io.write("\027[00m");
278 function show_yesno(prompt)
279 io.write(prompt, " ");
280 local choice = getchar():lower();
282 if not choice:match("%a") then
283 choice = prompt:match("%[.-(%U).-%]$");
284 if not choice then return nil; end
286 return (choice == "y");
289 local function read_password()
292 io.write("Enter new password: ");
293 password = getpass();
295 show_message("No password - cancelled");
298 io.write("Retype new password: ");
299 if getpass() ~= password then
300 if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then
310 local prosodyctl_timeout = (config.get("*", "core", "prosodyctl_timeout") or 5) * 2;
311 -----------------------
313 local command = arg[1];
315 function commands.adduser(arg)
316 if not arg[1] or arg[1] == "--help" then
317 show_usage([[adduser JID]], [[Create 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 create]]
323 show_usage [[adduser 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 prosodyctl.user_exists{ user = user, host = host } then
339 show_message [[That user already exists]];
343 local password = read_password();
344 if not password then return 1; end
346 local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
348 if ok then return 0; end
354 function commands.passwd(arg)
355 if not arg[1] or arg[1] == "--help" then
356 show_usage([[passwd JID]], [[Set the password for the specified user account in 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, use prosodyctl adduser to create a new user]]
382 local password = read_password();
383 if not password then return 1; end
385 local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
387 if ok then return 0; end
389 show_message(error_messages[msg])
393 function commands.deluser(arg)
394 if not arg[1] or arg[1] == "--help" then
395 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
398 local user, host = arg[1]:match("([^@]+)@(.+)");
399 if not user and host then
400 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
401 show_usage [[passwd user@host]]
406 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
410 if not hosts[host] then
411 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
412 show_warning("The user will not be able to log in until this is changed.");
413 hosts[host] = make_host(host);
416 if not prosodyctl.user_exists { user = user, host = host } then
417 show_message [[That user does not exist on this server]]
421 local ok, msg = prosodyctl.passwd { user = user, host = host };
423 if ok then return 0; end
425 show_message(error_messages[msg])
429 function commands.start(arg)
430 if arg[1] == "--help" then
431 show_usage([[start]], [[Start Prosody]]);
434 local ok, ret = prosodyctl.isrunning();
436 show_message(error_messages[ret]);
441 local ok, ret = prosodyctl.getpid();
443 show_message("Couldn't get running Prosody's PID");
444 show_message(error_messages[ret]);
447 show_message("Prosody is already running with PID %s", ret or "(unknown)");
451 local ok, ret = prosodyctl.start();
453 if config.get("*", "core", "daemonize") ~= false then
456 local ok, running = prosodyctl.isrunning();
457 if ok and running then
460 show_message("Still waiting...");
461 elseif i >= prosodyctl_timeout then
462 show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
468 show_message("Started");
473 show_message("Failed to start Prosody");
474 show_message(error_messages[ret])
478 function commands.status(arg)
479 if arg[1] == "--help" then
480 show_usage([[status]], [[Reports the running status of Prosody]]);
484 local ok, ret = prosodyctl.isrunning();
486 show_message(error_messages[ret]);
491 local ok, ret = prosodyctl.getpid();
493 show_message("Couldn't get running Prosody's PID");
494 show_message(error_messages[ret]);
497 show_message("Prosody is running with PID %s", ret or "(unknown)");
500 show_message("Prosody is not running");
501 if not switched_user and current_uid ~= 0 then
503 print(" You will also see this if prosodyctl is not running under");
504 print(" the same user account as Prosody. Try running as root (e.g. ");
505 print(" with 'sudo' in front) to gain access to Prosody's real status.");
512 function commands.stop(arg)
513 if arg[1] == "--help" then
514 show_usage([[stop]], [[Stop a running Prosody server]]);
518 if not prosodyctl.isrunning() then
519 show_message("Prosody is not running");
523 local ok, ret = prosodyctl.stop();
527 local ok, running = prosodyctl.isrunning();
528 if ok and not running then
531 show_message("Still waiting...");
532 elseif i >= prosodyctl_timeout then
533 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
539 show_message("Stopped");
543 show_message(error_messages[ret]);
547 function commands.restart(arg)
548 if arg[1] == "--help" then
549 show_usage([[restart]], [[Restart a running Prosody server]]);
554 return commands.start(arg);
557 -- ejabberdctl compatibility
559 function commands.register(arg)
560 local user, host, password = unpack(arg);
561 if (not (user and host)) or arg[1] == "--help" then
562 if user ~= "--help" then
564 show_message [[No username specified]]
566 show_message [[Please specify which host you want to register the user on]];
569 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
573 password = read_password();
575 show_message [[Unable to register user with no password]];
580 local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
582 if ok then return 0; end
584 show_message(error_messages[msg])
588 function commands.unregister(arg)
589 local user, host = unpack(arg);
590 if (not (user and host)) or arg[1] == "--help" then
591 if user ~= "--help" then
593 show_message [[No username specified]]
595 show_message [[Please specify which host you want to unregister the user from]];
598 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
602 local ok, msg = prosodyctl.deluser { user = user, host = host };
604 if ok then return 0; end
606 show_message(error_messages[msg])
610 ---------------------
612 if command and command:match("^mod_") then -- Is a command in a module
613 local module_name = command:match("^mod_(.+)");
614 local ret, err = modulemanager.load("*", module_name);
616 show_message("Failed to load module '"..module_name.."': "..err);
620 table.remove(arg, 1);
622 local module = modulemanager.get_module("*", module_name);
624 show_message("Failed to load module '"..module_name.."': Unknown error");
628 if not modulemanager.module_has_method(module, "command") then
629 show_message("Fail: mod_"..module_name.." does not support any commands");
633 local ok, ret = modulemanager.call_module_method(module, "command", arg);
635 if type(ret) == "number" then
637 elseif type(ret) == "string" then
642 show_message("Failed to execute command: "..error_messages[ret]);
647 if not commands[command] then -- Show help for all commands
648 function show_usage(usage, desc)
653 print("prosodyctl - Manage a Prosody server");
655 print("Usage: "..arg[0].." COMMAND [OPTIONS]");
657 print("Where COMMAND may be one of:\n");
659 local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
660 local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart" };
664 for _, command_name in ipairs(commands_order) do
665 local command = commands[command_name];
669 done[command_name] = true;
673 for command_name, command in pairs(commands) do
674 if not done[command_name] and not hidden_commands:contains(command_name) then
677 done[command_name] = true;
685 os.exit(commands[command]({ select(2, unpack(arg)) }));