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