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