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