prosodyctl: Add check that points out any disabled hosts
[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 prosodyctl_timeout = (config.get("*", "prosodyctl_timeout") or 5) * 2;
272 -----------------------
273 local commands = {};
274 local command = arg[1];
275
276 function commands.adduser(arg)
277         local jid_split = require "util.jid".split;
278         if not arg[1] or arg[1] == "--help" then
279                 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
280                 return 1;
281         end
282         local user, host = jid_split(arg[1]);
283         if not user and host then
284                 show_message [[Failed to understand JID, please supply the JID you want to create]]
285                 show_usage [[adduser user@host]]
286                 return 1;
287         end
288         
289         if not host then
290                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
291                 return 1;
292         end
293         
294         if not hosts[host] then
295                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
296                 show_warning("The user will not be able to log in until this is changed.");
297                 hosts[host] = make_host(host);
298         end
299         
300         if prosodyctl.user_exists{ user = user, host = host } then
301                 show_message [[That user already exists]];
302                 return 1;
303         end
304         
305         local password = read_password();
306         if not password then return 1; end
307         
308         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
309         
310         if ok then return 0; end
311         
312         show_message(msg)
313         return 1;
314 end
315
316 function commands.passwd(arg)
317         local jid_split = require "util.jid".split;
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         local jid_split = require "util.jid".split;
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                 show_warning("The user will not be able to log in until this is changed.");
377                 hosts[host] = make_host(host);
378         end
379
380         if not prosodyctl.user_exists { user = user, host = host } then
381                 show_message [[That user does not exist on this server]]
382                 return 1;
383         end
384         
385         local ok, msg = prosodyctl.deluser { user = user, host = host };
386         
387         if ok then return 0; end
388         
389         show_message(error_messages[msg])
390         return 1;
391 end
392
393 function commands.start(arg)
394         if arg[1] == "--help" then
395                 show_usage([[start]], [[Start Prosody]]);
396                 return 1;
397         end
398         local ok, ret = prosodyctl.isrunning();
399         if not ok then
400                 show_message(error_messages[ret]);
401                 return 1;
402         end
403         
404         if ret then
405                 local ok, ret = prosodyctl.getpid();
406                 if not ok then
407                         show_message("Couldn't get running Prosody's PID");
408                         show_message(error_messages[ret]);
409                         return 1;
410                 end
411                 show_message("Prosody is already running with PID %s", ret or "(unknown)");
412                 return 1;
413         end
414         
415         local ok, ret = prosodyctl.start();
416         if ok then
417                 local daemonize = config.get("*", "daemonize");
418                 if daemonize == nil then
419                         daemonize = prosody.installed;
420                 end
421                 if daemonize then
422                         local i=1;
423                         while true do
424                                 local ok, running = prosodyctl.isrunning();
425                                 if ok and running then
426                                         break;
427                                 elseif i == 5 then
428                                         show_message("Still waiting...");
429                                 elseif i >= prosodyctl_timeout then
430                                         show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
431                                         return 2;
432                                 end
433                                 socket.sleep(0.5);
434                                 i = i + 1;
435                         end
436                         show_message("Started");
437                 end
438                 return 0;
439         end
440
441         show_message("Failed to start Prosody");
442         show_message(error_messages[ret])       
443         return 1;       
444 end
445
446 function commands.status(arg)
447         if arg[1] == "--help" then
448                 show_usage([[status]], [[Reports the running status of Prosody]]);
449                 return 1;
450         end
451
452         local ok, ret = prosodyctl.isrunning();
453         if not ok then
454                 show_message(error_messages[ret]);
455                 return 1;
456         end
457         
458         if ret then
459                 local ok, ret = prosodyctl.getpid();
460                 if not ok then
461                         show_message("Couldn't get running Prosody's PID");
462                         show_message(error_messages[ret]);
463                         return 1;
464                 end
465                 show_message("Prosody is running with PID %s", ret or "(unknown)");
466                 return 0;
467         else
468                 show_message("Prosody is not running");
469                 if not switched_user and current_uid ~= 0 then
470                         print("\nNote:")
471                         print(" You will also see this if prosodyctl is not running under");
472                         print(" the same user account as Prosody. Try running as root (e.g. ");
473                         print(" with 'sudo' in front) to gain access to Prosody's real status.");
474                 end
475                 return 2
476         end
477         return 1;
478 end
479
480 function commands.stop(arg)
481         if arg[1] == "--help" then
482                 show_usage([[stop]], [[Stop a running Prosody server]]);
483                 return 1;
484         end
485
486         if not prosodyctl.isrunning() then
487                 show_message("Prosody is not running");
488                 return 1;
489         end
490         
491         local ok, ret = prosodyctl.stop();
492         if ok then
493                 local i=1;
494                 while true do
495                         local ok, running = prosodyctl.isrunning();
496                         if ok and not running then
497                                 break;
498                         elseif i == 5 then
499                                 show_message("Still waiting...");
500                         elseif i >= prosodyctl_timeout then
501                                 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
502                                 return 2;
503                         end
504                         socket.sleep(0.5);
505                         i = i + 1;
506                 end
507                 show_message("Stopped");
508                 return 0;
509         end
510
511         show_message(error_messages[ret]);
512         return 1;
513 end
514
515 function commands.restart(arg)
516         if arg[1] == "--help" then
517                 show_usage([[restart]], [[Restart a running Prosody server]]);
518                 return 1;
519         end
520         
521         commands.stop(arg);
522         return commands.start(arg);
523 end
524
525 function commands.about(arg)
526         read_version();
527         if arg[1] == "--help" then
528                 show_usage([[about]], [[Show information about this Prosody installation]]);
529                 return 1;
530         end
531         
532         local array = require "util.array";
533         local keys = require "util.iterators".keys;
534         
535         print("Prosody "..(prosody.version or "(unknown version)"));
536         print("");
537         print("# Prosody directories");
538         print("Data directory:  ", CFG_DATADIR or "./");
539         print("Plugin directory:", CFG_PLUGINDIR or "./");
540         print("Config directory:", CFG_CONFIGDIR or "./");
541         print("Source directory:", CFG_SOURCEDIR or "./");
542         print("");
543         print("# Lua environment");
544         print("Lua version:             ", _G._VERSION);
545         print("");
546         print("Lua module search paths:");
547         for path in package.path:gmatch("[^;]+") do
548                 print("  "..path);
549         end
550         print("");
551         print("Lua C module search paths:");
552         for path in package.cpath:gmatch("[^;]+") do
553                 print("  "..path);
554         end
555         print("");
556         local luarocks_status = (pcall(require, "luarocks.loader") and "Installed ("..(luarocks.cfg.program_version or "2.x+")..")")
557                 or (pcall(require, "luarocks.require") and "Installed (1.x)")
558                 or "Not installed";
559         print("LuaRocks:        ", luarocks_status);
560         print("");
561         print("# Lua module versions");
562         local module_versions, longest_name = {}, 8;
563         for name, module in pairs(package.loaded) do
564                 if type(module) == "table" and rawget(module, "_VERSION")
565                 and name ~= "_G" and not name:match("%.") then
566                         if #name > longest_name then
567                                 longest_name = #name;
568                         end
569                         module_versions[name] = module._VERSION;
570                 end
571         end
572         local sorted_keys = array.collect(keys(module_versions)):sort();
573         for _, name in ipairs(array.collect(keys(module_versions)):sort()) do
574                 print(name..":"..string.rep(" ", longest_name-#name), module_versions[name]);
575         end
576         print("");
577 end
578
579 function commands.reload(arg)
580         if arg[1] == "--help" then
581                 show_usage([[reload]], [[Reload Prosody's configuration and re-open log files]]);
582                 return 1;
583         end
584
585         if not prosodyctl.isrunning() then
586                 show_message("Prosody is not running");
587                 return 1;
588         end
589         
590         local ok, ret = prosodyctl.reload();
591         if ok then
592                 
593                 show_message("Prosody log files re-opened and config file reloaded. You may need to reload modules for some changes to take effect.");
594                 return 0;
595         end
596
597         show_message(error_messages[ret]);
598         return 1;
599 end
600 -- ejabberdctl compatibility
601
602 function commands.register(arg)
603         local user, host, password = unpack(arg);
604         if (not (user and host)) or arg[1] == "--help" then
605                 if user ~= "--help" then
606                         if not user then
607                                 show_message [[No username specified]]
608                         elseif not host then
609                                 show_message [[Please specify which host you want to register the user on]];
610                         end
611                 end
612                 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
613                 return 1;
614         end
615         if not password then
616                 password = read_password();
617                 if not password then
618                         show_message [[Unable to register user with no password]];
619                         return 1;
620                 end
621         end
622         
623         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
624         
625         if ok then return 0; end
626         
627         show_message(error_messages[msg])
628         return 1;
629 end
630
631 function commands.unregister(arg)
632         local user, host = unpack(arg);
633         if (not (user and host)) or arg[1] == "--help" then
634                 if user ~= "--help" then
635                         if not user then
636                                 show_message [[No username specified]]
637                         elseif not host then
638                                 show_message [[Please specify which host you want to unregister the user from]];
639                         end
640                 end
641                 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
642                 return 1;
643         end
644
645         local ok, msg = prosodyctl.deluser { user = user, host = host };
646         
647         if ok then return 0; end
648         
649         show_message(error_messages[msg])
650         return 1;
651 end
652
653 local openssl;
654 local lfs;
655
656 local cert_commands = {};
657
658 local function ask_overwrite(filename)
659         return lfs.attributes(filename) and not show_yesno("Overwrite "..filename .. "?");
660 end
661
662 function cert_commands.config(arg)
663         if #arg >= 1 and arg[1] ~= "--help" then
664                 local conf_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".cnf";
665                 if ask_overwrite(conf_filename) then
666                         return nil, conf_filename;
667                 end
668                 local conf = openssl.config.new();
669                 conf:from_prosody(hosts, config, arg);
670                 show_message("Please provide details to include in the certificate config file.");
671                 show_message("Leave the field empty to use the default value or '.' to exclude the field.")
672                 for i, k in ipairs(openssl._DN_order) do
673                         local v = conf.distinguished_name[k];
674                         if v then
675                                 local nv;
676                                 if k == "commonName" then
677                                         v = arg[1]
678                                 elseif k == "emailAddress" then
679                                         v = "xmpp@" .. arg[1];
680                                 elseif k == "countryName" then
681                                         local tld = arg[1]:match"%.([a-z]+)$";
682                                         if tld and #tld == 2 and tld ~= "uk" then
683                                                 v = tld:upper();
684                                         end
685                                 end
686                                 nv = show_prompt(("%s (%s):"):format(k, nv or v));
687                                 nv = (not nv or nv == "") and v or nv;
688                                 if nv:find"[\192-\252][\128-\191]+" then
689                                         conf.req.string_mask = "utf8only"
690                                 end
691                                 conf.distinguished_name[k] = nv ~= "." and nv or nil;
692                         end
693                 end
694                 local conf_file, err = io.open(conf_filename, "w");
695                 if not conf_file then
696                         show_warning("Could not open OpenSSL config file for writing");
697                         show_warning(err);
698                         os.exit(1);
699                 end
700                 conf_file:write(conf:serialize());
701                 conf_file:close();
702                 print("");
703                 show_message("Config written to " .. conf_filename);
704                 return nil, conf_filename;
705         else
706                 show_usage("cert config HOSTNAME [HOSTNAME+]", "Builds a certificate config file covering the supplied hostname(s)")
707         end
708 end
709
710 function cert_commands.key(arg)
711         if #arg >= 1 and arg[1] ~= "--help" then
712                 local key_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".key";
713                 if ask_overwrite(key_filename) then
714                         return nil, key_filename;
715                 end
716                 os.remove(key_filename); -- This file, if it exists is unlikely to have write permissions
717                 local key_size = tonumber(arg[2] or show_prompt("Choose key size (2048):") or 2048);
718                 local old_umask = pposix.umask("0377");
719                 if openssl.genrsa{out=key_filename, key_size} then
720                         os.execute(("chmod 400 '%s'"):format(key_filename));
721                         show_message("Key written to ".. key_filename);
722                         pposix.umask(old_umask);
723                         return nil, key_filename;
724                 end
725                 show_message("There was a problem, see OpenSSL output");
726         else
727                 show_usage("cert key HOSTNAME <bits>", "Generates a RSA key named HOSTNAME.key\n "
728                 .."Prompts for a key size if none given")
729         end
730 end
731
732 function cert_commands.request(arg)
733         if #arg >= 1 and arg[1] ~= "--help" then
734                 local req_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".req";
735                 if ask_overwrite(req_filename) then
736                         return nil, req_filename;
737                 end
738                 local _, key_filename = cert_commands.key({arg[1]});
739                 local _, conf_filename = cert_commands.config(arg);
740                 if openssl.req{new=true, key=key_filename, utf8=true, config=conf_filename, out=req_filename} then
741                         show_message("Certificate request written to ".. req_filename);
742                 else
743                         show_message("There was a problem, see OpenSSL output");
744                 end
745         else
746                 show_usage("cert request HOSTNAME [HOSTNAME+]", "Generates a certificate request for the supplied hostname(s)")
747         end
748 end
749
750 function cert_commands.generate(arg)
751         if #arg >= 1 and arg[1] ~= "--help" then
752                 local cert_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".crt";
753                 if ask_overwrite(cert_filename) then
754                         return nil, cert_filename;
755                 end
756                 local _, key_filename = cert_commands.key({arg[1]});
757                 local _, conf_filename = cert_commands.config(arg);
758                 local ret;
759                 if key_filename and conf_filename and cert_filename
760                         and openssl.req{new=true, x509=true, nodes=true, key=key_filename,
761                                 days=365, sha1=true, utf8=true, config=conf_filename, out=cert_filename} then
762                         show_message("Certificate written to ".. cert_filename);
763                 else
764                         show_message("There was a problem, see OpenSSL output");
765                 end
766         else
767                 show_usage("cert generate HOSTNAME [HOSTNAME+]", "Generates a self-signed certificate for the current hostname(s)")
768         end
769 end
770
771 function commands.cert(arg)
772         if #arg >= 1 and arg[1] ~= "--help" then
773                 openssl = require "util.openssl";
774                 lfs = require "lfs";
775                 local subcmd = table.remove(arg, 1);
776                 if type(cert_commands[subcmd]) == "function" then
777                         if not arg[1] then
778                                 show_message"You need to supply at least one hostname"
779                                 arg = { "--help" };
780                         end
781                         if arg[1] ~= "--help" and not hosts[arg[1]] then
782                                 show_message(error_messages["no-such-host"]);
783                                 return
784                         end
785                         return cert_commands[subcmd](arg);
786                 end
787         end
788         show_usage("cert config|request|generate|key", "Helpers for generating X.509 certificates and keys.")
789 end
790
791 function commands.check(arg)
792         if arg[1] == "--help" then
793                 show_usage([[check]], [[Perform basic checks on your Prosody installation]]);
794                 return 1;
795         end
796         local what = table.remove(arg, 1);
797         local array, set = require "util.array", require "util.set";
798         local it = require "util.iterators";
799         local ok = true;
800         local function disabled_hosts(host, conf) return host ~= "*" and conf.enabled ~= false; end
801         local function enabled_hosts() return it.filter(disabled_hosts, pairs(config.getconfig())); end
802         if not what or what == "disabled" then
803                 local disabled_hosts = set.new();
804                 for host, host_options in it.filter("*", pairs(config.getconfig())) do
805                         if host_options.enabled == false then
806                                 disabled_hosts:add(host);
807                         end
808                 end
809                 if not disabled_hosts:empty() then
810                         local msg = "Checks will be skipped for these disabled hosts: %s";
811                         if what then msg = "These hosts are disabled: %s"; end
812                         show_warning(msg, tostring(disabled_hosts));
813                         if what then return 0; end
814                         print""
815                 end
816         end
817         if not what or what == "config" then
818                 print("Checking config...");
819                 local known_global_options = set.new({
820                         "pidfile", "log", "plugin_paths", "prosody_user", "prosody_group", "daemonize",
821                         "umask", "prosodyctl_timeout", "use_ipv6", "use_libevent", "network_settings"
822                 });
823                 local config = config.getconfig();
824                 -- Check that we have any global options (caused by putting a host at the top)
825                 if it.count(it.filter("log", pairs(config["*"]))) == 0 then
826                         ok = false;
827                         print("");
828                         print("    No global options defined. Perhaps you have put a host definition at the top")
829                         print("    of the config file? They should be at the bottom, see http://prosody.im/doc/configure#overview");
830                 end
831                 -- Check for global options under hosts
832                 local global_options = set.new(it.to_array(it.keys(config["*"])));
833                 for host, options in enabled_hosts() do
834                         local host_options = set.new(it.to_array(it.keys(options)));
835                         local misplaced_options = set.intersection(host_options, known_global_options);
836                         for name in pairs(options) do
837                                 if name:match("^interfaces?")
838                                 or name:match("_ports?$") or name:match("_interfaces?$")
839                                 or name:match("_ssl$") then
840                                         misplaced_options:add(name);
841                                 end
842                         end
843                         if not misplaced_options:empty() then
844                                 ok = false;
845                                 print("");
846                                 local n = it.count(misplaced_options);
847                                 print("    You have "..n.." option"..(n>1 and "s " or " ").."set under "..host.." that should be");
848                                 print("    in the global section of the config file, above any VirtualHost or Component definitions,")
849                                 print("    see http://prosody.im/doc/configure#overview for more information.")
850                                 print("");
851                                 print("    You need to move the following option"..(n>1 and "s" or "")..": "..table.concat(it.to_array(misplaced_options), ", "));
852                         end
853                         local subdomain = host:match("^[^.]+");
854                         if not(host_options:contains("component_module")) and (subdomain == "jabber" or subdomain == "xmpp"
855                            or subdomain == "chat" or subdomain == "im") then
856                                 print("");
857                                 print("    Suggestion: If "..host.. " is a new host with no real users yet, consider renaming it now to");
858                                 print("     "..host:gsub("^[^.]+%.", "")..". You can use SRV records to redirect XMPP clients and servers to "..host..".");
859                                 print("     For more information see: http://prosody.im/doc/dns");
860                         end
861                 end
862                 
863                 print("Done.\n");
864         end
865         if not what or what == "dns" then
866                 local dns = require "net.dns";
867                 local idna = require "util.encodings".idna;
868                 local ip = require "util.ip";
869                 local c2s_ports = set.new(config.get("*", "c2s_ports") or {5222});
870                 local s2s_ports = set.new(config.get("*", "s2s_ports") or {5269});
871                 
872                 local c2s_srv_required, s2s_srv_required;
873                 if not c2s_ports:contains(5222) then
874                         c2s_srv_required = true;
875                 end
876                 if not s2s_ports:contains(5269) then
877                         s2s_srv_required = true;
878                 end
879                 
880                 local problem_hosts = set.new();
881                 
882                 local external_addresses, internal_addresses = set.new(), set.new();
883                 
884                 local fqdn = socket.dns.tohostname(socket.dns.gethostname());
885                 if fqdn then
886                         local res = dns.lookup(idna.to_ascii(fqdn), "A");
887                         if res then
888                                 for _, record in ipairs(res) do
889                                         external_addresses:add(record.a);
890                                 end
891                         end
892                         local res = dns.lookup(idna.to_ascii(fqdn), "AAAA");
893                         if res then
894                                 for _, record in ipairs(res) do
895                                         external_addresses:add(record.aaaa);
896                                 end
897                         end
898                 end
899                 
900                 local local_addresses = require"util.net".local_addresses() or {};
901                 
902                 for addr in it.values(local_addresses) do
903                         if not ip.new_ip(addr).private then
904                                 external_addresses:add(addr);
905                         else
906                                 internal_addresses:add(addr);
907                         end
908                 end
909                 
910                 if external_addresses:empty() then
911                         print("");
912                         print("   Failed to determine the external addresses of this server. Checks may be inaccurate.");
913                         c2s_srv_required, s2s_srv_required = true, true;
914                 end
915                 
916                 local v6_supported = not not socket.tcp6;
917                 
918                 for host, host_options in enabled_hosts() do
919                         local all_targets_ok, some_targets_ok = true, false;
920                         
921                         local is_component = not not host_options.component_module;
922                         print("Checking DNS for "..(is_component and "component" or "host").." "..host.."...");
923                         local target_hosts = set.new();
924                         if not is_component then
925                                 local res = dns.lookup("_xmpp-client._tcp."..idna.to_ascii(host)..".", "SRV");
926                                 if res then
927                                         for _, record in ipairs(res) do
928                                                 target_hosts:add(record.srv.target);
929                                                 if not c2s_ports:contains(record.srv.port) then
930                                                         print("    SRV target "..record.srv.target.." contains unknown client port: "..record.srv.port);
931                                                 end
932                                         end
933                                 else
934                                         if c2s_srv_required then
935                                                 print("    No _xmpp-client SRV record found for "..host..", but it looks like you need one.");
936                                                 all_targst_ok = false;
937                                         else
938                                                 target_hosts:add(host);
939                                         end
940                                 end
941                         end
942                         local res = dns.lookup("_xmpp-server._tcp."..idna.to_ascii(host)..".", "SRV");
943                         if res then
944                                 for _, record in ipairs(res) do
945                                         target_hosts:add(record.srv.target);
946                                         if not s2s_ports:contains(record.srv.port) then
947                                                 print("    SRV target "..record.srv.target.." contains unknown server port: "..record.srv.port);
948                                         end
949                                 end
950                         else
951                                 if s2s_srv_required then
952                                         print("    No _xmpp-server SRV record found for "..host..", but it looks like you need one.");
953                                         all_targets_ok = false;
954                                 else
955                                         target_hosts:add(host);
956                                 end
957                         end
958                         if target_hosts:empty() then
959                                 target_hosts:add(host);
960                         end
961                         
962                         if target_hosts:contains("localhost") then
963                                 print("    Target 'localhost' cannot be accessed from other servers");
964                                 target_hosts:remove("localhost");
965                         end
966                         
967                         local modules = set.new(it.to_array(it.values(host_options.modules_enabled)))
968                                         + set.new(it.to_array(it.values(config.get("*", "modules_enabled"))))
969                                         + set.new({ config.get(host, "component_module") });
970
971                         if modules:contains("proxy65") then
972                                 local proxy65_target = config.get(host, "proxy65_address") or host;
973                                 local A, AAAA = dns.lookup(idna.to_ascii(proxy65_target), "A"), dns.lookup(idna.to_ascii(proxy65_target), "AAAA");
974                                 local prob = {};
975                                 if not A then
976                                         table.insert(prob, "A");
977                                 end
978                                 if v6_supported and not AAAA then
979                                         table.insert(prob, "AAAA");
980                                 end
981                                 if #prob > 0 then
982                                         print("    File transfer proxy "..proxy65_target.." has no "..table.concat(prob, "/").." record. Create one or set 'proxy65_address' to the correct host/IP.");
983                                 end
984                         end
985                         
986                         for host in target_hosts do
987                                 local host_ok_v4, host_ok_v6;
988                                 local res = dns.lookup(idna.to_ascii(host), "A");
989                                 if res then
990                                         for _, record in ipairs(res) do
991                                                 if external_addresses:contains(record.a) then
992                                                         some_targets_ok = true;
993                                                         host_ok_v4 = true;
994                                                 elseif internal_addresses:contains(record.a) then
995                                                         host_ok_v4 = true;
996                                                         some_targets_ok = true;
997                                                         print("    "..host.." A record points to internal address, external connections might fail");
998                                                 else
999                                                         print("    "..host.." A record points to unknown address "..record.a);
1000                                                         all_targets_ok = false;
1001                                                 end
1002                                         end
1003                                 end
1004                                 local res = dns.lookup(idna.to_ascii(host), "AAAA");
1005                                 if res then
1006                                         for _, record in ipairs(res) do
1007                                                 if external_addresses:contains(record.aaaa) then
1008                                                         some_targets_ok = true;
1009                                                         host_ok_v6 = true;
1010                                                 elseif internal_addresses:contains(record.aaaa) then
1011                                                         host_ok_v6 = true;
1012                                                         some_targets_ok = true;
1013                                                         print("    "..host.." AAAA record points to internal address, external connections might fail");
1014                                                 else
1015                                                         print("    "..host.." AAAA record points to unknown address "..record.aaaa);
1016                                                         all_targets_ok = false;
1017                                                 end
1018                                         end
1019                                 end
1020                                 
1021                                 local bad_protos = {}
1022                                 if not host_ok_v4 then
1023                                         table.insert(bad_protos, "IPv4");
1024                                 end
1025                                 if not host_ok_v6 then
1026                                         table.insert(bad_protos, "IPv6");
1027                                 end
1028                                 if #bad_protos > 0 then
1029                                         print("    Host "..host.." does not seem to resolve to this server ("..table.concat(bad_protos, "/")..")");
1030                                 end
1031                                 if host_ok_v6 and not v6_supported then
1032                                         print("    Host "..host.." has AAAA records, but your version of LuaSocket does not support IPv6.");
1033                                         print("      Please see http://prosody.im/doc/ipv6 for more information.");
1034                                 end
1035                         end
1036                         if not all_targets_ok then
1037                                 print("    "..(some_targets_ok and "Only some" or "No").." targets for "..host.." appear to resolve to this server.");
1038                                 if is_component then
1039                                         print("    DNS records are necessary if you want users on other servers to access this component.");
1040                                 end
1041                                 problem_hosts:add(host);
1042                         end
1043                         print("");
1044                 end
1045                 if not problem_hosts:empty() then
1046                         print("");
1047                         print("For more information about DNS configuration please see http://prosody.im/doc/dns");
1048                         print("");
1049                         ok = false;
1050                 end
1051         end
1052         if not what or what == "certs" then
1053                 local cert_ok;
1054                 print"Checking certificates..."
1055                 local x509_verify_identity = require"util.x509".verify_identity;
1056                 local ssl = dependencies.softreq"ssl";
1057                 -- local datetime_parse = require"util.datetime".parse_x509;
1058                 local load_cert = ssl and ssl.x509 and ssl.x509.load;
1059                 -- or ssl.cert_from_pem
1060                 if not ssl then
1061                         print("LuaSec not available, can't perform certificate checks")
1062                         if what == "certs" then cert_ok = false end
1063                 elseif not load_cert then
1064                         print("This version of LuaSec (" .. ssl._VERSION .. ") does not support certificate checking");
1065                         cert_ok = false
1066                 else
1067                         for host in enabled_hosts() do
1068                                 print("Checking certificate for "..host);
1069                                 -- First, let's find out what certificate this host uses.
1070                                 local ssl_config = config.rawget(host, "ssl");
1071                                 if not ssl_config then
1072                                         local base_host = host:match("%.(.*)");
1073                                         ssl_config = config.get(base_host, "ssl");
1074                                 end
1075                                 if not ssl_config then
1076                                         print("  No 'ssl' option defined for "..host)
1077                                         cert_ok = false
1078                                 elseif not ssl_config.certificate then
1079                                         print("  No 'certificate' set in ssl option for "..host)
1080                                         cert_ok = false
1081                                 elseif not ssl_config.key then
1082                                         print("  No 'key' set in ssl option for "..host)
1083                                         cert_ok = false
1084                                 else
1085                                         local key, err = io.open(ssl_config.key); -- Permissions check only
1086                                         if not key then
1087                                                 print("    Could not open "..ssl_config.key..": "..err);
1088                                                 cert_ok = false
1089                                         else
1090                                                 key:close();
1091                                         end
1092                                         local cert_fh, err = io.open(ssl_config.certificate); -- Load the file.
1093                                         if not cert_fh then
1094                                                 print("    Could not open "..ssl_config.certificate..": "..err);
1095                                                 cert_ok = false
1096                                         else
1097                                                 print("  Certificate: "..ssl_config.certificate)
1098                                                 local cert = load_cert(cert_fh:read"*a"); cert_fh = cert_fh:close();
1099                                                 if not cert:validat(os.time()) then
1100                                                         print("    Certificate has expired.")
1101                                                         cert_ok = false
1102                                                 end
1103                                                 if config.get(host, "component_module") == nil
1104                                                         and not x509_verify_identity(host, "_xmpp-client", cert) then
1105                                                         print("    Not vaild for client connections to "..host..".")
1106                                                         cert_ok = false
1107                                                 end
1108                                                 if (not (config.get(name, "anonymous_login")
1109                                                         or config.get(name, "authentication") == "anonymous"))
1110                                                         and not x509_verify_identity(host, "_xmpp-client", cert) then
1111                                                         print("    Not vaild for server-to-server connections to "..host..".")
1112                                                         cert_ok = false
1113                                                 end
1114                                         end
1115                                 end
1116                         end
1117                         if cert_ok == false then
1118                                 print("")
1119                                 print("For more information about certificates please see http://prosody.im/doc/certificates");
1120                                 ok = false
1121                         end
1122                 end
1123                 print("")
1124         end
1125         if not ok then
1126                 print("Problems found, see above.");
1127         else
1128                 print("All checks passed, congratulations!");
1129         end
1130         return ok and 0 or 2;
1131 end
1132
1133 ---------------------
1134
1135 if command and command:match("^mod_") then -- Is a command in a module
1136         local module_name = command:match("^mod_(.+)");
1137         local ret, err = modulemanager.load("*", module_name);
1138         if not ret then
1139                 show_message("Failed to load module '"..module_name.."': "..err);
1140                 os.exit(1);
1141         end
1142         
1143         table.remove(arg, 1);
1144         
1145         local module = modulemanager.get_module("*", module_name);
1146         if not module then
1147                 show_message("Failed to load module '"..module_name.."': Unknown error");
1148                 os.exit(1);
1149         end
1150         
1151         if not modulemanager.module_has_method(module, "command") then
1152                 show_message("Fail: mod_"..module_name.." does not support any commands");
1153                 os.exit(1);
1154         end
1155         
1156         local ok, ret = modulemanager.call_module_method(module, "command", arg);
1157         if ok then
1158                 if type(ret) == "number" then
1159                         os.exit(ret);
1160                 elseif type(ret) == "string" then
1161                         show_message(ret);
1162                 end
1163                 os.exit(0); -- :)
1164         else
1165                 show_message("Failed to execute command: "..error_messages[ret]);
1166                 os.exit(1); -- :(
1167         end
1168 end
1169
1170 if not commands[command] then -- Show help for all commands
1171         function show_usage(usage, desc)
1172                 print(" "..usage);
1173                 print("    "..desc);
1174         end
1175
1176         print("prosodyctl - Manage a Prosody server");
1177         print("");
1178         print("Usage: "..arg[0].." COMMAND [OPTIONS]");
1179         print("");
1180         print("Where COMMAND may be one of:\n");
1181
1182         local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
1183         local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart", "reload", "about" };
1184
1185         local done = {};
1186
1187         for _, command_name in ipairs(commands_order) do
1188                 local command = commands[command_name];
1189                 if command then
1190                         command{ "--help" };
1191                         print""
1192                         done[command_name] = true;
1193                 end
1194         end
1195
1196         for command_name, command in pairs(commands) do
1197                 if not done[command_name] and not hidden_commands:contains(command_name) then
1198                         command{ "--help" };
1199                         print""
1200                         done[command_name] = true;
1201                 end
1202         end
1203         
1204         
1205         os.exit(0);
1206 end
1207
1208 os.exit(commands[command]({ select(2, unpack(arg)) }));