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