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