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