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