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