Merge 0.10->trunk
[prosody.git] / prosodyctl
1 #!/usr/bin/env lua
2 -- Prosody IM
3 -- Copyright (C) 2008-2010 Matthew Wild
4 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- 
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
8 --
9
10 -- prosodyctl - command-line controller for Prosody XMPP server
11
12 -- Will be modified by configure script if run --
13
14 CFG_SOURCEDIR=CFG_SOURCEDIR or os.getenv("PROSODY_SRCDIR");
15 CFG_CONFIGDIR=CFG_CONFIGDIR or os.getenv("PROSODY_CFGDIR");
16 CFG_PLUGINDIR=CFG_PLUGINDIR or os.getenv("PROSODY_PLUGINDIR");
17 CFG_DATADIR=CFG_DATADIR or 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 https://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 https://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 https://prosody.im/doc/prosodyctl#pidfile for help";
223                 ["invalid-pidfile"] = "The 'pidfile' option in the configuration file is not a string, see https://prosody.im/doc/prosodyctl#pidfile for help";
224                 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see https://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                 sessions = {},
237                 users = require "core.usermanager".new_null_provider(hostname)
238         };
239 end
240
241 for hostname, config in pairs(config.getconfig()) do
242         hosts[hostname] = make_host(hostname);
243 end
244         
245 local modulemanager = require "core.modulemanager"
246
247 local prosodyctl = require "util.prosodyctl"
248 local socket = require "socket"
249 -----------------------
250
251  -- FIXME: Duplicate code waiting for util.startup
252 function read_version()
253         -- Try to determine version
254         local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
255         prosody.version = "unknown";
256         if version_file then
257                 prosody.version = version_file:read("*a"):gsub("%s*$", "");
258                 version_file:close();
259                 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
260                         prosody.version = "hg:"..prosody.version;
261                 end
262         else
263                 local hg = require"util.mercurial";
264                 local hgid = hg.check_id(CFG_SOURCEDIR or ".");
265                 if hgid then prosody.version = "hg:" .. hgid; end
266         end
267 end
268
269 local show_message, show_warning = prosodyctl.show_message, prosodyctl.show_warning;
270 local show_usage = prosodyctl.show_usage;
271 local getchar, getpass = prosodyctl.getchar, prosodyctl.getpass;
272 local show_yesno = prosodyctl.show_yesno;
273 local show_prompt = prosodyctl.show_prompt;
274 local read_password = prosodyctl.read_password;
275
276 local jid_split = require "util.jid".prepped_split;
277
278 local prosodyctl_timeout = (config.get("*", "prosodyctl_timeout") or 5) * 2;
279 -----------------------
280 local commands = {};
281 local command = arg[1];
282
283 function commands.adduser(arg)
284         if not arg[1] or arg[1] == "--help" then
285                 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
286                 return 1;
287         end
288         local user, host = jid_split(arg[1]);
289         if not user and host then
290                 show_message [[Failed to understand JID, please supply the JID you want to create]]
291                 show_usage [[adduser user@host]]
292                 return 1;
293         end
294         
295         if not host then
296                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
297                 return 1;
298         end
299         
300         if not hosts[host] then
301                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
302                 show_warning("The user will not be able to log in until this is changed.");
303                 hosts[host] = make_host(host);
304         end
305         
306         if prosodyctl.user_exists{ user = user, host = host } then
307                 show_message [[That user already exists]];
308                 return 1;
309         end
310         
311         local password = read_password();
312         if not password then return 1; end
313         
314         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
315         
316         if ok then return 0; end
317         
318         show_message(msg)
319         return 1;
320 end
321
322 function commands.passwd(arg)
323         if not arg[1] or arg[1] == "--help" then
324                 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
325                 return 1;
326         end
327         local user, host = jid_split(arg[1]);
328         if not user and host then
329                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
330                 show_usage [[passwd user@host]]
331                 return 1;
332         end
333         
334         if not host then
335                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
336                 return 1;
337         end
338         
339         if not hosts[host] then
340                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
341                 show_warning("The user will not be able to log in until this is changed.");
342                 hosts[host] = make_host(host);
343         end
344         
345         if not prosodyctl.user_exists { user = user, host = host } then
346                 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
347                 return 1;
348         end
349         
350         local password = read_password();
351         if not password then return 1; end
352         
353         local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
354         
355         if ok then return 0; end
356         
357         show_message(error_messages[msg])
358         return 1;
359 end
360
361 function commands.deluser(arg)
362         if not arg[1] or arg[1] == "--help" then
363                 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
364                 return 1;
365         end
366         local user, host = jid_split(arg[1]);
367         if not user and host then
368                 show_message [[Failed to understand JID, please supply the JID to the user account you want to delete]]
369                 show_usage [[deluser user@host]]
370                 return 1;
371         end
372         
373         if not host then
374                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
375                 return 1;
376         end
377         
378         if not hosts[host] then
379                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
380                 hosts[host] = make_host(host);
381         end
382
383         if not prosodyctl.user_exists { user = user, host = host } then
384                 show_message [[That user does not exist on this server]]
385                 return 1;
386         end
387         
388         local ok, msg = prosodyctl.deluser { user = user, host = host };
389         
390         if ok then return 0; end
391         
392         show_message(error_messages[msg])
393         return 1;
394 end
395
396 function commands.start(arg)
397         if arg[1] == "--help" then
398                 show_usage([[start]], [[Start Prosody]]);
399                 return 1;
400         end
401         local ok, ret = prosodyctl.isrunning();
402         if not ok then
403                 show_message(error_messages[ret]);
404                 return 1;
405         end
406         
407         if ret then
408                 local ok, ret = prosodyctl.getpid();
409                 if not ok then
410                         show_message("Couldn't get running Prosody's PID");
411                         show_message(error_messages[ret]);
412                         return 1;
413                 end
414                 show_message("Prosody is already running with PID %s", ret or "(unknown)");
415                 return 1;
416         end
417         
418         local ok, ret = prosodyctl.start();
419         if ok then
420                 local daemonize = config.get("*", "daemonize");
421                 if daemonize == nil then
422                         daemonize = prosody.installed;
423                 end
424                 if daemonize then
425                         local i=1;
426                         while true do
427                                 local ok, running = prosodyctl.isrunning();
428                                 if ok and running then
429                                         break;
430                                 elseif i == 5 then
431                                         show_message("Still waiting...");
432                                 elseif i >= prosodyctl_timeout then
433                                         show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
434                                         return 2;
435                                 end
436                                 socket.sleep(0.5);
437                                 i = i + 1;
438                         end
439                         show_message("Started");
440                 end
441                 return 0;
442         end
443
444         show_message("Failed to start Prosody");
445         show_message(error_messages[ret])       
446         return 1;       
447 end
448
449 function commands.status(arg)
450         if arg[1] == "--help" then
451                 show_usage([[status]], [[Reports the running status of Prosody]]);
452                 return 1;
453         end
454
455         local ok, ret = prosodyctl.isrunning();
456         if not ok then
457                 show_message(error_messages[ret]);
458                 return 1;
459         end
460         
461         if ret then
462                 local ok, ret = prosodyctl.getpid();
463                 if not ok then
464                         show_message("Couldn't get running Prosody's PID");
465                         show_message(error_messages[ret]);
466                         return 1;
467                 end
468                 show_message("Prosody is running with PID %s", ret or "(unknown)");
469                 return 0;
470         else
471                 show_message("Prosody is not running");
472                 if not switched_user and current_uid ~= 0 then
473                         print("\nNote:")
474                         print(" You will also see this if prosodyctl is not running under");
475                         print(" the same user account as Prosody. Try running as root (e.g. ");
476                         print(" with 'sudo' in front) to gain access to Prosody's real status.");
477                 end
478                 return 2
479         end
480         return 1;
481 end
482
483 function commands.stop(arg)
484         if arg[1] == "--help" then
485                 show_usage([[stop]], [[Stop a running Prosody server]]);
486                 return 1;
487         end
488
489         if not prosodyctl.isrunning() then
490                 show_message("Prosody is not running");
491                 return 1;
492         end
493         
494         local ok, ret = prosodyctl.stop();
495         if ok then
496                 local i=1;
497                 while true do
498                         local ok, running = prosodyctl.isrunning();
499                         if ok and not running then
500                                 break;
501                         elseif i == 5 then
502                                 show_message("Still waiting...");
503                         elseif i >= prosodyctl_timeout then
504                                 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
505                                 return 2;
506                         end
507                         socket.sleep(0.5);
508                         i = i + 1;
509                 end
510                 show_message("Stopped");
511                 return 0;
512         end
513
514         show_message(error_messages[ret]);
515         return 1;
516 end
517
518 function commands.restart(arg)
519         if arg[1] == "--help" then
520                 show_usage([[restart]], [[Restart a running Prosody server]]);
521                 return 1;
522         end
523         
524         commands.stop(arg);
525         return commands.start(arg);
526 end
527
528 function commands.about(arg)
529         read_version();
530         if arg[1] == "--help" then
531                 show_usage([[about]], [[Show information about this Prosody installation]]);
532                 return 1;
533         end
534         
535         local pwd = ".";
536         local lfs = require "lfs";
537         local array = require "util.array";
538         local keys = require "util.iterators".keys;
539         local hg = require"util.mercurial";
540         local relpath = config.resolve_relative_path;
541         
542         print("Prosody "..(prosody.version or "(unknown version)"));
543         print("");
544         print("# Prosody directories");
545         print("Data directory:     "..relpath(pwd, data_path));
546         print("Config directory:   "..relpath(pwd, CFG_CONFIGDIR or "."));
547         print("Source directory:   "..relpath(pwd, CFG_SOURCEDIR or "."));
548         print("Plugin directories:")
549         print("  "..(prosody.paths.plugins:gsub("([^;]+);?", function(path)
550                         local opath = path;
551                         path = config.resolve_relative_path(pwd, path);
552                         local hgid, hgrepo = hg.check_id(path);
553                         if not hgid and hgrepo then
554                                 return path.." - "..hgrepo .."!\n  ";
555                         end
556                         -- 010452cfaf53 is the first commit in the prosody-modules repository
557                         hgrepo = hgrepo == "010452cfaf53" and "prosody-modules";
558                         return path..(hgid and " - "..(hgrepo or "HG").." rev: "..hgid or "")
559                                 .."\n  ";
560                 end)));
561         print("");
562         print("# Lua environment");
563         print("Lua version:             ", _G._VERSION);
564         print("");
565         print("Lua module search paths:");
566         for path in package.path:gmatch("[^;]+") do
567                 print("  "..path);
568         end
569         print("");
570         print("Lua C module search paths:");
571         for path in package.cpath:gmatch("[^;]+") do
572                 print("  "..path);
573         end
574         print("");
575         local luarocks_status = (pcall(require, "luarocks.loader") and "Installed ("..(package.loaded["luarocks.cfg"].program_version or "2.x+")..")")
576                 or (pcall(require, "luarocks.require") and "Installed (1.x)")
577                 or "Not installed";
578         print("LuaRocks:        ", luarocks_status);
579         print("");
580         print("# Lua module versions");
581         local module_versions, longest_name = {}, 8;
582         local luaevent =dependencies.softreq"luaevent";
583         local ssl = dependencies.softreq"ssl";
584         for name, module in pairs(package.loaded) do
585                 if type(module) == "table" and rawget(module, "_VERSION")
586                 and name ~= "_G" and not name:match("%.") then
587                         if #name > longest_name then
588                                 longest_name = #name;
589                         end
590                         module_versions[name] = module._VERSION;
591                 end
592         end
593         if luaevent then
594                 module_versions["libevent"] = luaevent.core.libevent_version();
595         end
596         local sorted_keys = array.collect(keys(module_versions)):sort();
597         for _, name in ipairs(sorted_keys) do
598                 print(name..":"..string.rep(" ", longest_name-#name), module_versions[name]);
599         end
600         print("");
601 end
602
603 function commands.reload(arg)
604         if arg[1] == "--help" then
605                 show_usage([[reload]], [[Reload Prosody's configuration and re-open log files]]);
606                 return 1;
607         end
608
609         if not prosodyctl.isrunning() then
610                 show_message("Prosody is not running");
611                 return 1;
612         end
613         
614         local ok, ret = prosodyctl.reload();
615         if ok then
616                 
617                 show_message("Prosody log files re-opened and config file reloaded. You may need to reload modules for some changes to take effect.");
618                 return 0;
619         end
620
621         show_message(error_messages[ret]);
622         return 1;
623 end
624 -- ejabberdctl compatibility
625
626 function commands.register(arg)
627         local user, host, password = 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 register the user on]];
634                         end
635                 end
636                 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
637                 return 1;
638         end
639         if not password then
640                 password = read_password();
641                 if not password then
642                         show_message [[Unable to register user with no password]];
643                         return 1;
644                 end
645         end
646         
647         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
648         
649         if ok then return 0; end
650         
651         show_message(error_messages[msg])
652         return 1;
653 end
654
655 function commands.unregister(arg)
656         local user, host = unpack(arg);
657         if (not (user and host)) or arg[1] == "--help" then
658                 if user ~= "--help" then
659                         if not user then
660                                 show_message [[No username specified]]
661                         elseif not host then
662                                 show_message [[Please specify which host you want to unregister the user from]];
663                         end
664                 end
665                 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
666                 return 1;
667         end
668
669         local ok, msg = prosodyctl.deluser { user = user, host = host };
670         
671         if ok then return 0; end
672         
673         show_message(error_messages[msg])
674         return 1;
675 end
676
677 local openssl;
678 local lfs;
679
680 local cert_commands = {};
681
682 -- If a file already exists, ask if the user wants to use it or replace it
683 -- Backups the old file if replaced
684 local function use_existing(filename)
685         local attrs = lfs.attributes(filename);
686         if attrs then
687                 if show_yesno(filename .. " exists, do you want to replace it? [y/n]") then
688                         local backup = filename..".bkp~"..os.date("%FT%T", attrs.change);
689                         os.rename(filename, backup);
690                         show_message(filename.." backed up to "..backup);
691                 else
692                         -- Use the existing file
693                         return true;
694                 end
695         end
696 end
697
698 function cert_commands.config(arg)
699         if #arg >= 1 and arg[1] ~= "--help" then
700                 local conf_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".cnf";
701                 if use_existing(conf_filename) then
702                         return nil, conf_filename;
703                 end
704                 local distinguished_name;
705                 if arg[#arg]:find("^/") then
706                         distinguished_name = table.remove(arg);
707                 end
708                 local conf = openssl.config.new();
709                 conf:from_prosody(hosts, config, arg);
710                 if distinguished_name then
711                         local dn = {};
712                         for k, v in distinguished_name:gmatch("/([^=/]+)=([^/]+)") do
713                                 table.insert(dn, k);
714                                 dn[k] = v;
715                         end
716                         conf.distinguished_name = dn;
717                 else
718                         show_message("Please provide details to include in the certificate config file.");
719                         show_message("Leave the field empty to use the default value or '.' to exclude the field.")
720                         for _, k in ipairs(openssl._DN_order) do
721                                 local v = conf.distinguished_name[k];
722                                 if v then
723                                         local nv;
724                                         if k == "commonName" then
725                                                 v = arg[1]
726                                         elseif k == "emailAddress" then
727                                                 v = "xmpp@" .. arg[1];
728                                         elseif k == "countryName" then
729                                                 local tld = arg[1]:match"%.([a-z]+)$";
730                                                 if tld and #tld == 2 and tld ~= "uk" then
731                                                         v = tld:upper();
732                                                 end
733                                         end
734                                         nv = show_prompt(("%s (%s):"):format(k, nv or v));
735                                         nv = (not nv or nv == "") and v or nv;
736                                         if nv:find"[\192-\252][\128-\191]+" then
737                                                 conf.req.string_mask = "utf8only"
738                                         end
739                                         conf.distinguished_name[k] = nv ~= "." and nv or nil;
740                                 end
741                         end
742                 end
743                 local conf_file, err = io.open(conf_filename, "w");
744                 if not conf_file then
745                         show_warning("Could not open OpenSSL config file for writing");
746                         show_warning(err);
747                         os.exit(1);
748                 end
749                 conf_file:write(conf:serialize());
750                 conf_file:close();
751                 print("");
752                 show_message("Config written to " .. conf_filename);
753                 return nil, conf_filename;
754         else
755                 show_usage("cert config HOSTNAME [HOSTNAME+]", "Builds a certificate config file covering the supplied hostname(s)")
756         end
757 end
758
759 function cert_commands.key(arg)
760         if #arg >= 1 and arg[1] ~= "--help" then
761                 local key_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".key";
762                 if use_existing(key_filename) then
763                         return nil, key_filename;
764                 end
765                 os.remove(key_filename); -- This file, if it exists is unlikely to have write permissions
766                 local key_size = tonumber(arg[2] or show_prompt("Choose key size (2048):") or 2048);
767                 local old_umask = pposix.umask("0377");
768                 if openssl.genrsa{out=key_filename, key_size} then
769                         os.execute(("chmod 400 '%s'"):format(key_filename));
770                         show_message("Key written to ".. key_filename);
771                         pposix.umask(old_umask);
772                         return nil, key_filename;
773                 end
774                 show_message("There was a problem, see OpenSSL output");
775         else
776                 show_usage("cert key HOSTNAME <bits>", "Generates a RSA key named HOSTNAME.key\n "
777                 .."Prompts for a key size if none given")
778         end
779 end
780
781 function cert_commands.request(arg)
782         if #arg >= 1 and arg[1] ~= "--help" then
783                 local req_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".req";
784                 if use_existing(req_filename) then
785                         return nil, req_filename;
786                 end
787                 local _, key_filename = cert_commands.key({arg[1]});
788                 local _, conf_filename = cert_commands.config(arg);
789                 if openssl.req{new=true, key=key_filename, utf8=true, sha256=true, config=conf_filename, out=req_filename} then
790                         show_message("Certificate request written to ".. req_filename);
791                 else
792                         show_message("There was a problem, see OpenSSL output");
793                 end
794         else
795                 show_usage("cert request HOSTNAME [HOSTNAME+]", "Generates a certificate request for the supplied hostname(s)")
796         end
797 end
798
799 function cert_commands.generate(arg)
800         if #arg >= 1 and arg[1] ~= "--help" then
801                 local cert_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".crt";
802                 if use_existing(cert_filename) then
803                         return nil, cert_filename;
804                 end
805                 local _, key_filename = cert_commands.key({arg[1]});
806                 local _, conf_filename = cert_commands.config(arg);
807                 local ret;
808                 if key_filename and conf_filename and cert_filename
809                         and openssl.req{new=true, x509=true, nodes=true, key=key_filename,
810                                 days=365, sha256=true, utf8=true, config=conf_filename, out=cert_filename} then
811                         show_message("Certificate written to ".. cert_filename);
812                         print();
813                         show_message(("Example config:\n\nssl = {\n\tcertificate = %q;\n\tkey = %q;\n}"):format(cert_filename, key_filename));
814                 else
815                         show_message("There was a problem, see OpenSSL output");
816                 end
817         else
818                 show_usage("cert generate HOSTNAME [HOSTNAME+]", "Generates a self-signed certificate for the current hostname(s)")
819         end
820 end
821
822 function commands.cert(arg)
823         if #arg >= 1 and arg[1] ~= "--help" then
824                 openssl = require "util.openssl";
825                 lfs = require "lfs";
826                 local subcmd = table.remove(arg, 1);
827                 if type(cert_commands[subcmd]) == "function" then
828                         if not arg[1] then
829                                 show_message"You need to supply at least one hostname"
830                                 arg = { "--help" };
831                         end
832                         if arg[1] ~= "--help" and not hosts[arg[1]] then
833                                 show_message(error_messages["no-such-host"]);
834                                 return
835                         end
836                         return cert_commands[subcmd](arg);
837                 end
838         end
839         show_usage("cert config|request|generate|key", "Helpers for generating X.509 certificates and keys.")
840 end
841
842 function commands.check(arg)
843         if arg[1] == "--help" then
844                 show_usage([[check]], [[Perform basic checks on your Prosody installation]]);
845                 return 1;
846         end
847         local what = table.remove(arg, 1);
848         local array, set = require "util.array", require "util.set";
849         local it = require "util.iterators";
850         local ok = true;
851         local function disabled_hosts(host, conf) return host ~= "*" and conf.enabled ~= false; end
852         local function enabled_hosts() return it.filter(disabled_hosts, pairs(config.getconfig())); end
853         if not what or what == "disabled" then
854                 local disabled_hosts = set.new();
855                 for host, host_options in it.filter("*", pairs(config.getconfig())) do
856                         if host_options.enabled == false then
857                                 disabled_hosts:add(host);
858                         end
859                 end
860                 if not disabled_hosts:empty() then
861                         local msg = "Checks will be skipped for these disabled hosts: %s";
862                         if what then msg = "These hosts are disabled: %s"; end
863                         show_warning(msg, tostring(disabled_hosts));
864                         if what then return 0; end
865                         print""
866                 end
867         end
868         if not what or what == "config" then
869                 print("Checking config...");
870                 local deprecated = set.new({
871                         "bosh_ports", "disallow_s2s", "no_daemonize", "anonymous_login", "require_encryption",
872                         "vcard_compatibility",
873                 });
874                 local known_global_options = set.new({
875                         "pidfile", "log", "plugin_paths", "prosody_user", "prosody_group", "daemonize",
876                         "umask", "prosodyctl_timeout", "use_ipv6", "use_libevent", "network_settings",
877                         "network_backend", "http_default_host",
878                 });
879                 local config = config.getconfig();
880                 -- Check that we have any global options (caused by putting a host at the top)
881                 if it.count(it.filter("log", pairs(config["*"]))) == 0 then
882                         ok = false;
883                         print("");
884                         print("    No global options defined. Perhaps you have put a host definition at the top")
885                         print("    of the config file? They should be at the bottom, see https://prosody.im/doc/configure#overview");
886                 end
887                 if it.count(enabled_hosts()) == 0 then
888                         ok = false;
889                         print("");
890                         if it.count(it.filter("*", pairs(config))) == 0 then
891                                 print("    No hosts are defined, please add at least one VirtualHost section")
892                         elseif config["*"]["enabled"] == false then
893                                 print("    No hosts are enabled. Remove enabled = false from the global section or put enabled = true under at least one VirtualHost section")
894                         else
895                                 print("    All hosts are disabled. Remove enabled = false from at least one VirtualHost section")
896                         end
897                 end
898                 if not config["*"].modules_enabled then
899                         print("    No global modules_enabled is set?");
900                         local suggested_global_modules;
901                         for host, options in enabled_hosts() do
902                                 if not options.component_module and options.modules_enabled then
903                                         suggested_global_modules = set.intersection(suggested_global_modules or set.new(options.modules_enabled), set.new(options.modules_enabled));
904                                 end
905                         end
906                         if not suggested_global_modules:empty() then
907                                 print("    Consider moving these modules into modules_enabled in the global section:")
908                                 print("    "..tostring(suggested_global_modules / function (x) return ("%q"):format(x) end));
909                         end
910                         print();
911                 end
912                 -- Check for global options under hosts
913                 local global_options = set.new(it.to_array(it.keys(config["*"])));
914                 local deprecated_global_options = set.intersection(global_options, deprecated);
915                 if not deprecated_global_options:empty() then
916                         print("");
917                         print("    You have some deprecated options in the global section:");
918                         print("    "..tostring(deprecated_global_options))
919                         ok = false;
920                 end
921                 for host, options in enabled_hosts() do
922                         local host_options = set.new(it.to_array(it.keys(options)));
923                         local misplaced_options = set.intersection(host_options, known_global_options);
924                         for name in pairs(options) do
925                                 if name:match("^interfaces?")
926                                 or name:match("_ports?$") or name:match("_interfaces?$")
927                                 or (name:match("_ssl$") and not name:match("^[cs]2s_ssl$")) then
928                                         misplaced_options:add(name);
929                                 end
930                         end
931                         if not misplaced_options:empty() then
932                                 ok = false;
933                                 print("");
934                                 local n = it.count(misplaced_options);
935                                 print("    You have "..n.." option"..(n>1 and "s " or " ").."set under "..host.." that should be");
936                                 print("    in the global section of the config file, above any VirtualHost or Component definitions,")
937                                 print("    see https://prosody.im/doc/configure#overview for more information.")
938                                 print("");
939                                 print("    You need to move the following option"..(n>1 and "s" or "")..": "..table.concat(it.to_array(misplaced_options), ", "));
940                         end
941                         local subdomain = host:match("^[^.]+");
942                         if not(host_options:contains("component_module")) and (subdomain == "jabber" or subdomain == "xmpp"
943                            or subdomain == "chat" or subdomain == "im") then
944                                 print("");
945                                 print("    Suggestion: If "..host.. " is a new host with no real users yet, consider renaming it now to");
946                                 print("     "..host:gsub("^[^.]+%.", "")..". You can use SRV records to redirect XMPP clients and servers to "..host..".");
947                                 print("     For more information see: https://prosody.im/doc/dns");
948                         end
949                 end
950                 local all_modules = set.new(config["*"].modules_enabled);
951                 local all_options = set.new(it.to_array(it.keys(config["*"])));
952                 for host in enabled_hosts() do
953                         all_options:include(set.new(it.to_array(it.keys(config[host]))));
954                         all_modules:include(set.new(config[host].modules_enabled));
955                 end
956                 for mod in all_modules do
957                         if mod:match("^mod_") then
958                                 print("");
959                                 print("    Modules in modules_enabled should not have the 'mod_' prefix included.");
960                                 print("    Change '"..mod.."' to '"..mod:match("^mod_(.*)").."'.");
961                         elseif mod:match("^auth_") then
962                                 print("");
963                                 print("    Authentication modules should not be added to modules_enabled,");
964                                 print("    but be specified in the 'authentication' option.");
965                                 print("    Remove '"..mod.."' from modules_enabled and instead add");
966                                 print("        authentication = '"..mod:match("^auth_(.*)").."'");
967                                 print("    For more information see https://prosody.im/doc/authentication");
968                         elseif mod:match("^storage_") then
969                                 print("");
970                                 print("    storage modules should not be added to modules_enabled,");
971                                 print("    but be specified in the 'storage' option.");
972                                 print("    Remove '"..mod.."' from modules_enabled and instead add");
973                                 print("        storage = '"..mod:match("^storage_(.*)").."'");
974                                 print("    For more information see https://prosody.im/doc/storage");
975                         end
976                 end
977                 local require_encryption = set.intersection(all_options, set.new({"require_encryption", "c2s_require_encryption", "s2s_require_encryption"})):empty();
978                 local ssl = dependencies.softreq"ssl";
979                 if not ssl then
980                         if not require_encryption then
981                                 print("");
982                                 print("    You require encryption but LuaSec is not available.");
983                                 print("    Connections will fail.");
984                                 ok = false;
985                         end
986                 elseif not ssl.loadcertificate then
987                         if all_options:contains("s2s_secure_auth") then
988                                 print("");
989                                 print("    You have set s2s_secure_auth but your version of LuaSec does ");
990                                 print("    not support certificate validation, so all s2s connections will");
991                                 print("    fail.");
992                                 ok = false;
993                         elseif all_options:contains("s2s_secure_domains") then
994                                 local secure_domains = set.new();
995                                 for host in enabled_hosts() do
996                                         if config[host].s2s_secure_auth == true then
997                                                 secure_domains:add("*");
998                                         else
999                                                 secure_domains:include(set.new(config[host].s2s_secure_domains));
1000                                         end
1001                                 end
1002                                 if not secure_domains:empty() then
1003                                         print("");
1004                                         print("    You have set s2s_secure_domains but your version of LuaSec does ");
1005                                         print("    not support certificate validation, so s2s connections to/from ");
1006                                         print("    these domains will fail.");
1007                                         ok = false;
1008                                 end
1009                         end
1010                 elseif require_encryption and not all_modules:contains("tls") then
1011                         print("");
1012                         print("    You require encryption but mod_tls is not enabled.");
1013                         print("    Connections will fail.");
1014                         ok = false;
1015                 end
1016                 
1017                 print("Done.\n");
1018         end
1019         if not what or what == "dns" then
1020                 local dns = require "net.dns";
1021                 local idna = require "util.encodings".idna;
1022                 local ip = require "util.ip";
1023                 local c2s_ports = set.new(config.get("*", "c2s_ports") or {5222});
1024                 local s2s_ports = set.new(config.get("*", "s2s_ports") or {5269});
1025                 
1026                 local c2s_srv_required, s2s_srv_required;
1027                 if not c2s_ports:contains(5222) then
1028                         c2s_srv_required = true;
1029                 end
1030                 if not s2s_ports:contains(5269) then
1031                         s2s_srv_required = true;
1032                 end
1033                 
1034                 local problem_hosts = set.new();
1035                 
1036                 local external_addresses, internal_addresses = set.new(), set.new();
1037                 
1038                 local fqdn = socket.dns.tohostname(socket.dns.gethostname());
1039                 if fqdn then
1040                         local res = dns.lookup(idna.to_ascii(fqdn), "A");
1041                         if res then
1042                                 for _, record in ipairs(res) do
1043                                         external_addresses:add(record.a);
1044                                 end
1045                         end
1046                         local res = dns.lookup(idna.to_ascii(fqdn), "AAAA");
1047                         if res then
1048                                 for _, record in ipairs(res) do
1049                                         external_addresses:add(record.aaaa);
1050                                 end
1051                         end
1052                 end
1053                 
1054                 local local_addresses = require"util.net".local_addresses() or {};
1055                 
1056                 for addr in it.values(local_addresses) do
1057                         if not ip.new_ip(addr).private then
1058                                 external_addresses:add(addr);
1059                         else
1060                                 internal_addresses:add(addr);
1061                         end
1062                 end
1063                 
1064                 if external_addresses:empty() then
1065                         print("");
1066                         print("   Failed to determine the external addresses of this server. Checks may be inaccurate.");
1067                         c2s_srv_required, s2s_srv_required = true, true;
1068                 end
1069                 
1070                 local v6_supported = not not socket.tcp6;
1071                 
1072                 for jid, host_options in enabled_hosts() do
1073                         local all_targets_ok, some_targets_ok = true, false;
1074                         local node, host = jid_split(jid);
1075                         
1076                         local is_component = not not host_options.component_module;
1077                         print("Checking DNS for "..(is_component and "component" or "host").." "..jid.."...");
1078                         if node then
1079                                 print("Only the domain part ("..host..") is used in DNS.")
1080                         end
1081                         local target_hosts = set.new();
1082                         if not is_component then
1083                                 local res = dns.lookup("_xmpp-client._tcp."..idna.to_ascii(host)..".", "SRV");
1084                                 if res then
1085                                         for _, record in ipairs(res) do
1086                                                 target_hosts:add(record.srv.target);
1087                                                 if not c2s_ports:contains(record.srv.port) then
1088                                                         print("    SRV target "..record.srv.target.." contains unknown client port: "..record.srv.port);
1089                                                 end
1090                                         end
1091                                 else
1092                                         if c2s_srv_required then
1093                                                 print("    No _xmpp-client SRV record found for "..host..", but it looks like you need one.");
1094                                                 all_targets_ok = false;
1095                                         else
1096                                                 target_hosts:add(host);
1097                                         end
1098                                 end
1099                         end
1100                         local res = dns.lookup("_xmpp-server._tcp."..idna.to_ascii(host)..".", "SRV");
1101                         if res then
1102                                 for _, record in ipairs(res) do
1103                                         target_hosts:add(record.srv.target);
1104                                         if not s2s_ports:contains(record.srv.port) then
1105                                                 print("    SRV target "..record.srv.target.." contains unknown server port: "..record.srv.port);
1106                                         end
1107                                 end
1108                         else
1109                                 if s2s_srv_required then
1110                                         print("    No _xmpp-server SRV record found for "..host..", but it looks like you need one.");
1111                                         all_targets_ok = false;
1112                                 else
1113                                         target_hosts:add(host);
1114                                 end
1115                         end
1116                         if target_hosts:empty() then
1117                                 target_hosts:add(host);
1118                         end
1119                         
1120                         if target_hosts:contains("localhost") then
1121                                 print("    Target 'localhost' cannot be accessed from other servers");
1122                                 target_hosts:remove("localhost");
1123                         end
1124                         
1125                         local modules = set.new(it.to_array(it.values(host_options.modules_enabled or {})))
1126                                         + set.new(it.to_array(it.values(config.get("*", "modules_enabled") or {})))
1127                                         + set.new({ config.get(host, "component_module") });
1128
1129                         if modules:contains("proxy65") then
1130                                 local proxy65_target = config.get(host, "proxy65_address") or host;
1131                                 local A, AAAA = dns.lookup(idna.to_ascii(proxy65_target), "A"), dns.lookup(idna.to_ascii(proxy65_target), "AAAA");
1132                                 local prob = {};
1133                                 if not A then
1134                                         table.insert(prob, "A");
1135                                 end
1136                                 if v6_supported and not AAAA then
1137                                         table.insert(prob, "AAAA");
1138                                 end
1139                                 if #prob > 0 then
1140                                         print("    File transfer proxy "..proxy65_target.." has no "..table.concat(prob, "/").." record. Create one or set 'proxy65_address' to the correct host/IP.");
1141                                 end
1142                         end
1143                         
1144                         for host in target_hosts do
1145                                 local host_ok_v4, host_ok_v6;
1146                                 local res = dns.lookup(idna.to_ascii(host), "A");
1147                                 if res then
1148                                         for _, record in ipairs(res) do
1149                                                 if external_addresses:contains(record.a) then
1150                                                         some_targets_ok = true;
1151                                                         host_ok_v4 = true;
1152                                                 elseif internal_addresses:contains(record.a) then
1153                                                         host_ok_v4 = true;
1154                                                         some_targets_ok = true;
1155                                                         print("    "..host.." A record points to internal address, external connections might fail");
1156                                                 else
1157                                                         print("    "..host.." A record points to unknown address "..record.a);
1158                                                         all_targets_ok = false;
1159                                                 end
1160                                         end
1161                                 end
1162                                 local res = dns.lookup(idna.to_ascii(host), "AAAA");
1163                                 if res then
1164                                         for _, record in ipairs(res) do
1165                                                 if external_addresses:contains(record.aaaa) then
1166                                                         some_targets_ok = true;
1167                                                         host_ok_v6 = true;
1168                                                 elseif internal_addresses:contains(record.aaaa) then
1169                                                         host_ok_v6 = true;
1170                                                         some_targets_ok = true;
1171                                                         print("    "..host.." AAAA record points to internal address, external connections might fail");
1172                                                 else
1173                                                         print("    "..host.." AAAA record points to unknown address "..record.aaaa);
1174                                                         all_targets_ok = false;
1175                                                 end
1176                                         end
1177                                 end
1178                                 
1179                                 local bad_protos = {}
1180                                 if not host_ok_v4 then
1181                                         table.insert(bad_protos, "IPv4");
1182                                 end
1183                                 if not host_ok_v6 then
1184                                         table.insert(bad_protos, "IPv6");
1185                                 end
1186                                 if #bad_protos > 0 then
1187                                         print("    Host "..host.." does not seem to resolve to this server ("..table.concat(bad_protos, "/")..")");
1188                                 end
1189                                 if host_ok_v6 and not v6_supported then
1190                                         print("    Host "..host.." has AAAA records, but your version of LuaSocket does not support IPv6.");
1191                                         print("      Please see https://prosody.im/doc/ipv6 for more information.");
1192                                 end
1193                         end
1194                         if not all_targets_ok then
1195                                 print("    "..(some_targets_ok and "Only some" or "No").." targets for "..host.." appear to resolve to this server.");
1196                                 if is_component then
1197                                         print("    DNS records are necessary if you want users on other servers to access this component.");
1198                                 end
1199                                 problem_hosts:add(host);
1200                         end
1201                         print("");
1202                 end
1203                 if not problem_hosts:empty() then
1204                         print("");
1205                         print("For more information about DNS configuration please see https://prosody.im/doc/dns");
1206                         print("");
1207                         ok = false;
1208                 end
1209         end
1210         if not what or what == "certs" then
1211                 local cert_ok;
1212                 print"Checking certificates..."
1213                 local x509_verify_identity = require"util.x509".verify_identity;
1214                 local create_context = require "core.certmanager".create_context;
1215                 local ssl = dependencies.softreq"ssl";
1216                 -- local datetime_parse = require"util.datetime".parse_x509;
1217                 local load_cert = ssl and ssl.loadcertificate;
1218                 -- or ssl.cert_from_pem
1219                 if not ssl then
1220                         print("LuaSec not available, can't perform certificate checks")
1221                         if what == "certs" then cert_ok = false end
1222                 elseif not load_cert then
1223                         print("This version of LuaSec (" .. ssl._VERSION .. ") does not support certificate checking");
1224                         cert_ok = false
1225                 else
1226                         for host in enabled_hosts() do
1227                                 print("Checking certificate for "..host);
1228                                 -- First, let's find out what certificate this host uses.
1229                                 local host_ssl_config = config.rawget(host, "ssl")
1230                                         or config.rawget(host:match("%.(.*)"), "ssl");
1231                                 local global_ssl_config = config.rawget("*", "ssl");
1232                                 local ok, err, ssl_config = create_context(host, "server", host_ssl_config, global_ssl_config);
1233                                 if not ok then
1234                                         print("  Error: "..err);
1235                                         cert_ok = false
1236                                 elseif not ssl_config.certificate then
1237                                         print("  No 'certificate' found for "..host)
1238                                         cert_ok = false
1239                                 elseif not ssl_config.key then
1240                                         print("  No 'key' found for "..host)
1241                                         cert_ok = false
1242                                 else
1243                                         local key, err = io.open(ssl_config.key); -- Permissions check only
1244                                         if not key then
1245                                                 print("    Could not open "..ssl_config.key..": "..err);
1246                                                 cert_ok = false
1247                                         else
1248                                                 key:close();
1249                                         end
1250                                         local cert_fh, err = io.open(ssl_config.certificate); -- Load the file.
1251                                         if not cert_fh then
1252                                                 print("    Could not open "..ssl_config.certificate..": "..err);
1253                                                 cert_ok = false
1254                                         else
1255                                                 print("  Certificate: "..ssl_config.certificate)
1256                                                 local cert = load_cert(cert_fh:read"*a"); cert_fh = cert_fh:close();
1257                                                 if not cert:validat(os.time()) then
1258                                                         print("    Certificate has expired.")
1259                                                         cert_ok = false
1260                                                 elseif not cert:validat(os.time() + 86400) then
1261                                                         print("    Certificate expires within one day.")
1262                                                         cert_ok = false
1263                                                 elseif not cert:validat(os.time() + 86400*7) then
1264                                                         print("    Certificate expires within one week.")
1265                                                 elseif not cert:validat(os.time() + 86400*31) then
1266                                                         print("    Certificate expires within one month.")
1267                                                 end
1268                                                 if config.get(host, "component_module") == nil
1269                                                         and not x509_verify_identity(host, "_xmpp-client", cert) then
1270                                                         print("    Not valid for client connections to "..host..".")
1271                                                         cert_ok = false
1272                                                 end
1273                                                 if (not (config.get(host, "anonymous_login")
1274                                                         or config.get(host, "authentication") == "anonymous"))
1275                                                         and not x509_verify_identity(host, "_xmpp-server", cert) then
1276                                                         print("    Not valid for server-to-server connections to "..host..".")
1277                                                         cert_ok = false
1278                                                 end
1279                                         end
1280                                 end
1281                         end
1282                         if cert_ok == false then
1283                                 print("")
1284                                 print("For more information about certificates please see https://prosody.im/doc/certificates");
1285                                 ok = false
1286                         end
1287                 end
1288                 print("")
1289         end
1290         if not ok then
1291                 print("Problems found, see above.");
1292         else
1293                 print("All checks passed, congratulations!");
1294         end
1295         return ok and 0 or 2;
1296 end
1297
1298 ---------------------
1299
1300 if command and command:match("^mod_") then -- Is a command in a module
1301         local module_name = command:match("^mod_(.+)");
1302         local ret, err = modulemanager.load("*", module_name);
1303         if not ret then
1304                 show_message("Failed to load module '"..module_name.."': "..err);
1305                 os.exit(1);
1306         end
1307         
1308         table.remove(arg, 1);
1309         
1310         local module = modulemanager.get_module("*", module_name);
1311         if not module then
1312                 show_message("Failed to load module '"..module_name.."': Unknown error");
1313                 os.exit(1);
1314         end
1315         
1316         if not modulemanager.module_has_method(module, "command") then
1317                 show_message("Fail: mod_"..module_name.." does not support any commands");
1318                 os.exit(1);
1319         end
1320         
1321         local ok, ret = modulemanager.call_module_method(module, "command", arg);
1322         if ok then
1323                 if type(ret) == "number" then
1324                         os.exit(ret);
1325                 elseif type(ret) == "string" then
1326                         show_message(ret);
1327                 end
1328                 os.exit(0); -- :)
1329         else
1330                 show_message("Failed to execute command: "..error_messages[ret]);
1331                 os.exit(1); -- :(
1332         end
1333 end
1334
1335 if not commands[command] then -- Show help for all commands
1336         function show_usage(usage, desc)
1337                 print(" "..usage);
1338                 print("    "..desc);
1339         end
1340
1341         print("prosodyctl - Manage a Prosody server");
1342         print("");
1343         print("Usage: "..arg[0].." COMMAND [OPTIONS]");
1344         print("");
1345         print("Where COMMAND may be one of:\n");
1346
1347         local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
1348         local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart", "reload", "about" };
1349
1350         local done = {};
1351
1352         for _, command_name in ipairs(commands_order) do
1353                 local command = commands[command_name];
1354                 if command then
1355                         command{ "--help" };
1356                         print""
1357                         done[command_name] = true;
1358                 end
1359         end
1360
1361         for command_name, command in pairs(commands) do
1362                 if not done[command_name] and not hidden_commands:contains(command_name) then
1363                         command{ "--help" };
1364                         print""
1365                         done[command_name] = true;
1366                 end
1367         end
1368         
1369         
1370         os.exit(0);
1371 end
1372
1373 os.exit(commands[command]({ select(2, unpack(arg)) }));