prosodyctl: Make sure hosts[*].modules always exists.
[prosody.git] / prosodyctl
1 #!/usr/bin/env lua
2 -- Prosody IM
3 -- Copyright (C) 2008-2010 Matthew Wild
4 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- 
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
8 --
9
10 -- prosodyctl - command-line controller for Prosody XMPP server
11
12 -- Will be modified by configure script if run --
13
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");
18
19 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20
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) ~= ":\\")))
25 end
26
27 -- Tell Lua where to find our libraries
28 if CFG_SOURCEDIR then
29         local function filter_relative_paths(path)
30                 if is_relative(path) then return ""; end
31         end
32         local function sanitise_paths(paths)
33                 return (paths:gsub("[^;]+;?", filter_relative_paths):gsub(";;+", ";"));
34         end
35         package.path = sanitise_paths(CFG_SOURCEDIR.."/?.lua;"..package.path);
36         package.cpath = sanitise_paths(CFG_SOURCEDIR.."/?.so;"..package.cpath);
37 end
38
39 -- Substitute ~ with path to home directory in data path
40 if CFG_DATADIR then
41         if os.getenv("HOME") then
42                 CFG_DATADIR = CFG_DATADIR:gsub("^~", os.getenv("HOME"));
43         end
44 end
45
46 -- Global 'prosody' object
47 local prosody = {
48         hosts = {};
49         events = require "util.events".new();
50         platform = "posix";
51         lock_globals = function () end;
52         unlock_globals = function () end;
53         installed = CFG_SOURCEDIR ~= nil;
54 };
55 _G.prosody = prosody;
56
57 local dependencies = require "util.dependencies";
58 if not dependencies.check_dependencies() then
59         os.exit(1);
60 end
61
62 config = require "core.configmanager"
63
64 do
65         local filenames = {};
66         
67         local filename;
68         if arg[1] == "--config" and arg[2] then
69                 table.insert(filenames, arg[2]);
70                 table.remove(arg, 1); table.remove(arg, 1);
71                 if CFG_CONFIGDIR then
72                         table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
73                 end
74         else
75                 for _, format in ipairs(config.parsers()) do
76                         table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
77                 end
78         end
79         for _,_filename in ipairs(filenames) do
80                 filename = _filename;
81                 local file = io.open(filename);
82                 if file then
83                         file:close();
84                         CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
85                         break;
86                 end
87         end
88         local ok, level, err = config.load(filename);
89         if not ok then
90                 print("\n");
91                 print("**************************");
92                 if level == "parser" then
93                         print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
94                         local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
95                         print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
96                         print("");
97                 elseif level == "file" then
98                         print("Prosody was unable to find the configuration file.");
99                         print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
100                         print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
101                         print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
102                 end
103                 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
104                 print("Good luck!");
105                 print("**************************");
106                 print("");
107                 os.exit(1);
108         end
109 end
110 local original_logging_config = config.get("*", "core", "log");
111 config.set("*", "core", "log", { { levels = { min="info" }, to = "console" } });
112
113 local data_path = config.get("*", "core", "data_path") or CFG_DATADIR or "data";
114 local custom_plugin_paths = config.get("*", "core", "plugin_paths");
115 if custom_plugin_paths then
116         local path_sep = package.config:sub(3,3);
117         -- path1;path2;path3;defaultpath...
118         CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
119 end
120 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
121                   plugins = CFG_PLUGINDIR or "plugins", data = data_path };
122
123 if prosody.installed then
124         -- Change working directory to data path.
125         require "lfs".chdir(data_path);
126 end
127
128 require "core.loggingmanager"
129
130 dependencies.log_warnings();
131
132 -- Switch away from root and into the prosody user --
133 local switched_user, current_uid;
134
135 local want_pposix_version = "0.3.5";
136 local ok, pposix = pcall(require, "util.pposix");
137
138 if ok and pposix then
139         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
140         current_uid = pposix.getuid();
141         if current_uid == 0 then
142                 -- We haz root!
143                 local desired_user = config.get("*", "core", "prosody_user") or "prosody";
144                 local desired_group = config.get("*", "core", "prosody_group") or desired_user;
145                 local ok, err = pposix.setgid(desired_group);
146                 if ok then
147                         ok, err = pposix.initgroups(desired_user);
148                 end
149                 if ok then
150                         ok, err = pposix.setuid(desired_user);
151                         if ok then
152                                 -- Yay!
153                                 switched_user = true;
154                         end
155                 end
156                 if not switched_user then
157                         -- Boo!
158                         print("Warning: Couldn't switch to Prosody user/group '"..tostring(desired_user).."'/'"..tostring(desired_group).."': "..tostring(err));
159                 end
160         end
161         
162         -- Set our umask to protect data files
163         pposix.umask(config.get("*", "core", "umask") or "027");
164 else
165         print("Error: Unable to load pposix module. Check that Prosody is installed correctly.")
166         print("For more help send the below error to us through http://prosody.im/discuss");
167         print(tostring(pposix))
168 end
169
170 local function test_writeable(filename)
171         local f, err = io.open(filename, "a");
172         if not f then
173                 return false, err;
174         end
175         f:close();
176         return true;
177 end
178
179 local unwriteable_files = {};
180 if type(original_logging_config) == "string" and original_logging_config:sub(1,1) ~= "*" then
181         local ok, err = test_writeable(original_logging_config);
182         if not ok then
183                 table.insert(unwriteable_files, err);
184         end
185 elseif type(original_logging_config) == "table" then
186         for _, rule in ipairs(original_logging_config) do
187                 if rule.filename then
188                         local ok, err = test_writeable(rule.filename);
189                         if not ok then
190                                 table.insert(unwriteable_files, err);
191                         end
192                 end
193         end
194 end
195
196 if #unwriteable_files > 0 then
197         print("One of more of the Prosody log files are not");
198         print("writeable, please correct the errors and try");
199         print("starting prosodyctl again.");
200         print("");
201         for _, err in ipairs(unwriteable_files) do
202                 print(err);
203         end
204         print("");
205         os.exit(1);
206 end
207
208
209 local error_messages = setmetatable({ 
210                 ["invalid-username"] = "The given username is invalid in a Jabber ID";
211                 ["invalid-hostname"] = "The given hostname is invalid";
212                 ["no-password"] = "No password was supplied";
213                 ["no-such-user"] = "The given user does not exist on the server";
214                 ["no-such-host"] = "The given hostname does not exist in the config";
215                 ["unable-to-save-data"] = "Unable to store, perhaps you don't have permission?";
216                 ["no-pidfile"] = "There is no 'pidfile' option in the configuration file, see http://prosody.im/doc/prosodyctl#pidfile for help";
217                 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see http://prosody.im/doc/prosodyctl for more info";
218                 ["no-such-method"] = "This module has no commands";
219                 ["not-running"] = "Prosody is not running";
220                 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
221
222 hosts = prosody.hosts;
223
224 local function make_host(hostname)
225         return {
226                 type = "local",
227                 events = prosody.events,
228                 modules = {},
229                 users = require "core.usermanager".new_null_provider(hostname)
230         };
231 end
232
233 for hostname, config in pairs(config.getconfig()) do
234         hosts[hostname] = make_host(hostname);
235 end
236         
237 local modulemanager = require "core.modulemanager"
238
239 local prosodyctl = require "util.prosodyctl"
240 require "socket"
241 -----------------------
242
243  -- FIXME: Duplicate code waiting for util.startup
244 function read_version()
245         -- Try to determine version
246         local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
247         if version_file then
248                 prosody.version = version_file:read("*a"):gsub("%s*$", "");
249                 version_file:close();
250                 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
251                         prosody.version = "hg:"..prosody.version;
252                 end
253         else
254                 prosody.version = "unknown";
255         end
256 end
257
258 local show_message, show_warning = prosodyctl.show_message, prosodyctl.show_warning;
259 local show_usage = prosodyctl.show_usage;
260 local getchar, getpass = prosodyctl.getchar, prosodyctl.getpass;
261 local show_yesno = prosodyctl.show_yesno;
262 local show_prompt = prosodyctl.show_prompt;
263 local read_password = prosodyctl.read_password;
264
265 local prosodyctl_timeout = (config.get("*", "core", "prosodyctl_timeout") or 5) * 2;
266 -----------------------
267 local commands = {};
268 local command = arg[1];
269
270 function commands.adduser(arg)
271         if not arg[1] or arg[1] == "--help" then
272                 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
273                 return 1;
274         end
275         local user, host = arg[1]:match("([^@]+)@(.+)");
276         if not user and host then
277                 show_message [[Failed to understand JID, please supply the JID you want to create]]
278                 show_usage [[adduser user@host]]
279                 return 1;
280         end
281         
282         if not host then
283                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
284                 return 1;
285         end
286         
287         if not hosts[host] then
288                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
289                 show_warning("The user will not be able to log in until this is changed.");
290                 hosts[host] = make_host(host);
291         end
292         
293         if prosodyctl.user_exists{ user = user, host = host } then
294                 show_message [[That user already exists]];
295                 return 1;
296         end
297         
298         local password = read_password();
299         if not password then return 1; end
300         
301         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
302         
303         if ok then return 0; end
304         
305         show_message(msg)
306         return 1;
307 end
308
309 function commands.passwd(arg)
310         if not arg[1] or arg[1] == "--help" then
311                 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
312                 return 1;
313         end
314         local user, host = arg[1]:match("([^@]+)@(.+)");
315         if not user and host then
316                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
317                 show_usage [[passwd user@host]]
318                 return 1;
319         end
320         
321         if not host then
322                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
323                 return 1;
324         end
325         
326         if not hosts[host] then
327                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
328                 show_warning("The user will not be able to log in until this is changed.");
329                 hosts[host] = make_host(host);
330         end
331         
332         if not prosodyctl.user_exists { user = user, host = host } then
333                 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
334                 return 1;
335         end
336         
337         local password = read_password();
338         if not password then return 1; end
339         
340         local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
341         
342         if ok then return 0; end
343         
344         show_message(error_messages[msg])
345         return 1;
346 end
347
348 function commands.deluser(arg)
349         if not arg[1] or arg[1] == "--help" then
350                 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
351                 return 1;
352         end
353         local user, host = arg[1]:match("([^@]+)@(.+)");
354         if not user and host then
355                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
356                 show_usage [[passwd user@host]]
357                 return 1;
358         end
359         
360         if not host then
361                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
362                 return 1;
363         end
364         
365         if not hosts[host] then
366                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
367                 show_warning("The user will not be able to log in until this is changed.");
368                 hosts[host] = make_host(host);
369         end
370
371         if not prosodyctl.user_exists { user = user, host = host } then
372                 show_message [[That user does not exist on this server]]
373                 return 1;
374         end
375         
376         local ok, msg = prosodyctl.deluser { user = user, host = host };
377         
378         if ok then return 0; end
379         
380         show_message(error_messages[msg])
381         return 1;
382 end
383
384 function commands.start(arg)
385         if arg[1] == "--help" then
386                 show_usage([[start]], [[Start Prosody]]);
387                 return 1;
388         end
389         local ok, ret = prosodyctl.isrunning();
390         if not ok then
391                 show_message(error_messages[ret]);
392                 return 1;
393         end
394         
395         if ret then
396                 local ok, ret = prosodyctl.getpid();
397                 if not ok then
398                         show_message("Couldn't get running Prosody's PID");
399                         show_message(error_messages[ret]);
400                         return 1;
401                 end
402                 show_message("Prosody is already running with PID %s", ret or "(unknown)");
403                 return 1;
404         end
405         
406         local ok, ret = prosodyctl.start();
407         if ok then
408                 if config.get("*", "core", "daemonize") ~= false then
409                         local i=1;
410                         while true do
411                                 local ok, running = prosodyctl.isrunning();
412                                 if ok and running then
413                                         break;
414                                 elseif i == 5 then
415                                         show_message("Still waiting...");
416                                 elseif i >= prosodyctl_timeout then
417                                         show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
418                                         return 2;
419                                 end
420                                 socket.sleep(0.5);
421                                 i = i + 1;
422                         end
423                         show_message("Started");
424                 end
425                 return 0;
426         end
427
428         show_message("Failed to start Prosody");
429         show_message(error_messages[ret])       
430         return 1;       
431 end
432
433 function commands.status(arg)
434         if arg[1] == "--help" then
435                 show_usage([[status]], [[Reports the running status of Prosody]]);
436                 return 1;
437         end
438
439         local ok, ret = prosodyctl.isrunning();
440         if not ok then
441                 show_message(error_messages[ret]);
442                 return 1;
443         end
444         
445         if ret then
446                 local ok, ret = prosodyctl.getpid();
447                 if not ok then
448                         show_message("Couldn't get running Prosody's PID");
449                         show_message(error_messages[ret]);
450                         return 1;
451                 end
452                 show_message("Prosody is running with PID %s", ret or "(unknown)");
453                 return 0;
454         else
455                 show_message("Prosody is not running");
456                 if not switched_user and current_uid ~= 0 then
457                         print("\nNote:")
458                         print(" You will also see this if prosodyctl is not running under");
459                         print(" the same user account as Prosody. Try running as root (e.g. ");
460                         print(" with 'sudo' in front) to gain access to Prosody's real status.");
461                 end
462                 return 2
463         end
464         return 1;
465 end
466
467 function commands.stop(arg)
468         if arg[1] == "--help" then
469                 show_usage([[stop]], [[Stop a running Prosody server]]);
470                 return 1;
471         end
472
473         if not prosodyctl.isrunning() then
474                 show_message("Prosody is not running");
475                 return 1;
476         end
477         
478         local ok, ret = prosodyctl.stop();
479         if ok then
480                 local i=1;
481                 while true do
482                         local ok, running = prosodyctl.isrunning();
483                         if ok and not running then
484                                 break;
485                         elseif i == 5 then
486                                 show_message("Still waiting...");
487                         elseif i >= prosodyctl_timeout then
488                                 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
489                                 return 2;
490                         end
491                         socket.sleep(0.5);
492                         i = i + 1;
493                 end
494                 show_message("Stopped");
495                 return 0;
496         end
497
498         show_message(error_messages[ret]);
499         return 1;
500 end
501
502 function commands.restart(arg)
503         if arg[1] == "--help" then
504                 show_usage([[restart]], [[Restart a running Prosody server]]);
505                 return 1;
506         end
507         
508         commands.stop(arg);
509         return commands.start(arg);
510 end
511
512 function commands.about(arg)
513         read_version();
514         if arg[1] == "--help" then
515                 show_usage([[about]], [[Show information about this Prosody installation]]);
516                 return 1;
517         end
518         
519         local array = require "util.array";
520         local keys = require "util.iterators".keys;
521         
522         print("Prosody "..(prosody.version or "(unknown version)"));
523         print("");
524         print("# Prosody directories");
525         print("Data directory:  ", CFG_DATADIR or "./");
526         print("Plugin directory:", CFG_PLUGINDIR or "./");
527         print("Config directory:", CFG_CONFIGDIR or "./");
528         print("Source directory:", CFG_SOURCEDIR or "./");
529         print("");
530         print("# Lua environment");
531         print("Lua version:             ", _G._VERSION);
532         print("");
533         print("Lua module search paths:");
534         for path in package.path:gmatch("[^;]+") do
535                 print("  "..path);
536         end
537         print("");
538         print("Lua C module search paths:");
539         for path in package.cpath:gmatch("[^;]+") do
540                 print("  "..path);
541         end
542         print("");
543         local luarocks_status = (pcall(require, "luarocks.loader") and "Installed ("..(luarocks.cfg.program_version or "2.x+")..")")
544                 or (pcall(require, "luarocks.require") and "Installed (1.x)")
545                 or "Not installed";
546         print("LuaRocks:        ", luarocks_status);
547         print("");
548         print("# Lua module versions");
549         local module_versions, longest_name = {}, 8;
550         for name, module in pairs(package.loaded) do
551                 if type(module) == "table" and rawget(module, "_VERSION")
552                 and name ~= "_G" and not name:match("%.") then
553                         if #name > longest_name then
554                                 longest_name = #name;
555                         end
556                         module_versions[name] = module._VERSION;
557                 end
558         end
559         local sorted_keys = array.collect(keys(module_versions)):sort();
560         for _, name in ipairs(array.collect(keys(module_versions)):sort()) do
561                 print(name..":"..string.rep(" ", longest_name-#name), module_versions[name]);
562         end
563         print("");
564 end
565
566 function commands.reload(arg)
567         if arg[1] == "--help" then
568                 show_usage([[reload]], [[Reload Prosody's configuration and re-open log files]]);
569                 return 1;
570         end
571
572         if not prosodyctl.isrunning() then
573                 show_message("Prosody is not running");
574                 return 1;
575         end
576         
577         local ok, ret = prosodyctl.reload();
578         if ok then
579                 
580                 show_message("Prosody log files re-opened and config file reloaded. You may need to reload modules for some changes to take effect.");
581                 return 0;
582         end
583
584         show_message(error_messages[ret]);
585         return 1;
586 end
587 -- ejabberdctl compatibility
588
589 function commands.register(arg)
590         local user, host, password = unpack(arg);
591         if (not (user and host)) or arg[1] == "--help" then
592                 if user ~= "--help" then
593                         if not user then
594                                 show_message [[No username specified]]
595                         elseif not host then
596                                 show_message [[Please specify which host you want to register the user on]];
597                         end
598                 end
599                 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
600                 return 1;
601         end
602         if not password then
603                 password = read_password();
604                 if not password then
605                         show_message [[Unable to register user with no password]];
606                         return 1;
607                 end
608         end
609         
610         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
611         
612         if ok then return 0; end
613         
614         show_message(error_messages[msg])
615         return 1;
616 end
617
618 function commands.unregister(arg)
619         local user, host = unpack(arg);
620         if (not (user and host)) or arg[1] == "--help" then
621                 if user ~= "--help" then
622                         if not user then
623                                 show_message [[No username specified]]
624                         elseif not host then
625                                 show_message [[Please specify which host you want to unregister the user from]];
626                         end
627                 end
628                 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
629                 return 1;
630         end
631
632         local ok, msg = prosodyctl.deluser { user = user, host = host };
633         
634         if ok then return 0; end
635         
636         show_message(error_messages[msg])
637         return 1;
638 end
639
640 local openssl = require "util.openssl";
641 local lfs = require "lfs";
642
643 local cert_commands = {};
644
645 local function ask_overwrite(filename)
646         return lfs.attributes(filename) and not show_yesno("Overwrite "..filename .. "?");
647 end
648
649 function cert_commands.config(arg)
650         if #arg >= 1 and arg[1] ~= "--help" then
651                 local conf_filename = (CFG_DATADIR or ".") .. "/" .. arg[1] .. ".cnf";
652                 if ask_overwrite(conf_filename) then
653                         return nil, conf_filename;
654                 end
655                 local conf = openssl.config.new();
656                 conf:from_prosody(hosts, config, arg);
657                 for k, v in pairs(conf.distinguished_name) do
658                         local nv;
659                         if k == "commonName" then 
660                                 v = arg[1]
661                         elseif k == "emailAddress" then
662                                 v = "xmpp@" .. arg[1];
663                         end
664                         nv = show_prompt(("%s (%s):"):format(k, nv or v));
665                         nv = (not nv or nv == "") and v or nv;
666                         if nv:find"[\192-\252][\128-\191]+" then
667                                 conf.req.string_mask = "utf8only"
668                         end
669                         conf.distinguished_name[k] = nv ~= "." and nv or nil;
670                 end
671                 local conf_file = io.open(conf_filename, "w");
672                 conf_file:write(conf:serialize());
673                 conf_file:close();
674                 print("");
675                 show_message("Config written to " .. conf_filename);
676                 return nil, conf_filename;
677         else
678                 show_usage("cert config HOSTNAME [HOSTNAME+]", "Builds a certificate config file covering the supplied hostname(s)")
679         end
680 end
681
682 function cert_commands.key(arg)
683         if #arg >= 1 and arg[1] ~= "--help" then
684                 local key_filename = (CFG_DATADIR or ".") .. "/" .. arg[1] .. ".key";
685                 if ask_overwrite(key_filename) then
686                         return nil, key_filename;
687                 end
688                 os.remove(key_filename); -- We chmod this file to not have write permissions
689                 local key_size = tonumber(arg[2] or show_prompt("Choose key size (2048):") or 2048);
690                 if openssl.genrsa{out=key_filename, key_size} then
691                         os.execute(("chmod 400 '%s'"):format(key_filename));
692                         show_message("Key written to ".. key_filename);
693                         return nil, key_filename;
694                 end
695                 show_message("There was a problem, see OpenSSL output");
696         else
697                 show_usage("cert key HOSTNAME <bits>", "Generates a RSA key named HOSTNAME.key\n "
698                 .."Prompts for a key size if none given")
699         end
700 end
701
702 function cert_commands.request(arg)
703         if #arg >= 1 and arg[1] ~= "--help" then
704                 local req_filename = (CFG_DATADIR or ".") .. "/" .. arg[1] .. ".req";
705                 if ask_overwrite(req_filename) then
706                         return nil, req_filename;
707                 end
708                 local _, key_filename = cert_commands.key({arg[1]});
709                 local _, conf_filename = cert_commands.config(arg);
710                 if openssl.req{new=true, key=key_filename, utf8=true, config=conf_filename, out=req_filename} then
711                         show_message("Certificate request written to ".. req_filename);
712                 else
713                         show_message("There was a problem, see OpenSSL output");
714                 end
715         else
716                 show_usage("cert request HOSTNAME [HOSTNAME+]", "Generates a certificate request for the supplied hostname(s)")
717         end
718 end
719
720 function cert_commands.generate(arg)
721         if #arg >= 1 and arg[1] ~= "--help" then
722                 local cert_filename = (CFG_DATADIR or ".") .. "/" .. arg[1] .. ".cert";
723                 if ask_overwrite(cert_filename) then
724                         return nil, conf_filename;
725                 end
726                 local _, key_filename = cert_commands.key({arg[1]});
727                 local _, conf_filename = cert_commands.config(arg);
728                 local ret;
729                 if key_filename and conf_filename and cert_filename
730                         and openssl.req{new=true, x509=true, nodes=true, key=key_filename,
731                                 days=365, sha1=true, utf8=true, config=conf_filename, out=cert_filename} then
732                         show_message("Certificate written to ".. cert_filename);
733                 else
734                         show_message("There was a problem, see OpenSSL output");
735                 end
736         else
737                 show_usage("cert generate HOSTNAME [HOSTNAME+]", "Generates a self-signed certificate for the current hostname(s)")
738         end
739 end
740
741 function commands.cert(arg)
742         if #arg >= 1 and arg[1] ~= "--help" then
743                 local subcmd = table.remove(arg, 1);
744                 if type(cert_commands[subcmd]) == "function" then
745                         if not arg[1] then
746                                 show_message"You need to supply at least one hostname"
747                                 arg = { "--help" };
748                         end
749                         if arg[1] ~= "--help" and not hosts[arg[1]] then
750                                 show_message(error_messages["no-such-host"]);
751                                 return
752                         end
753                         return cert_commands[subcmd](arg);
754                 end
755         end
756         show_usage("cert config|request|generate|key", "Helpers for generating X.509 certificates and keys.")
757 end
758
759 ---------------------
760
761 if command and command:match("^mod_") then -- Is a command in a module
762         local module_name = command:match("^mod_(.+)");
763         local ret, err = modulemanager.load("*", module_name);
764         if not ret then
765                 show_message("Failed to load module '"..module_name.."': "..err);
766                 os.exit(1);
767         end
768         
769         table.remove(arg, 1);
770         
771         local module = modulemanager.get_module("*", module_name);
772         if not module then
773                 show_message("Failed to load module '"..module_name.."': Unknown error");
774                 os.exit(1);
775         end
776         
777         if not modulemanager.module_has_method(module, "command") then
778                 show_message("Fail: mod_"..module_name.." does not support any commands");
779                 os.exit(1);
780         end
781         
782         local ok, ret = modulemanager.call_module_method(module, "command", arg);
783         if ok then
784                 if type(ret) == "number" then
785                         os.exit(ret);
786                 elseif type(ret) == "string" then
787                         show_message(ret);
788                 end
789                 os.exit(0); -- :)
790         else
791                 show_message("Failed to execute command: "..error_messages[ret]);
792                 os.exit(1); -- :(
793         end
794 end
795
796 if not commands[command] then -- Show help for all commands
797         function show_usage(usage, desc)
798                 print(" "..usage);
799                 print("    "..desc);
800         end
801
802         print("prosodyctl - Manage a Prosody server");
803         print("");
804         print("Usage: "..arg[0].." COMMAND [OPTIONS]");
805         print("");
806         print("Where COMMAND may be one of:\n");
807
808         local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
809         local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart", "reload", "about" };
810
811         local done = {};
812
813         for _, command_name in ipairs(commands_order) do
814                 local command = commands[command_name];
815                 if command then
816                         command{ "--help" };
817                         print""
818                         done[command_name] = true;
819                 end
820         end
821
822         for command_name, command in pairs(commands) do
823                 if not done[command_name] and not hidden_commands:contains(command_name) then
824                         command{ "--help" };
825                         print""
826                         done[command_name] = true;
827                 end
828         end
829         
830         
831         os.exit(0);
832 end
833
834 os.exit(commands[command]({ select(2, unpack(arg)) }));