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=os.getenv("PROSODY_SRCDIR");
15 CFG_CONFIGDIR=os.getenv("PROSODY_CFGDIR");
16 CFG_PLUGINDIR=os.getenv("PROSODY_PLUGINDIR");
17 CFG_DATADIR=os.getenv("PROSODY_DATADIR");
18
19 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20
21 local function is_relative(path)
22         local path_sep = package.config:sub(1,1);
23         return ((path_sep == "/" and path:sub(1,1) ~= "/")
24         or (path_sep == "\\" and (path:sub(1,1) ~= "/" and path:sub(2,3) ~= ":\\")))
25 end
26
27 -- Tell Lua where to find our libraries
28 if CFG_SOURCEDIR then
29         local function filter_relative_paths(path)
30                 if is_relative(path) then return ""; end
31         end
32         local function sanitise_paths(paths)
33                 return (paths:gsub("[^;]+;?", filter_relative_paths):gsub(";;+", ";"));
34         end
35         package.path = sanitise_paths(CFG_SOURCEDIR.."/?.lua;"..package.path);
36         package.cpath = sanitise_paths(CFG_SOURCEDIR.."/?.so;"..package.cpath);
37 end
38
39 -- Substitute ~ with path to home directory in data path
40 if CFG_DATADIR then
41         if os.getenv("HOME") then
42                 CFG_DATADIR = CFG_DATADIR:gsub("^~", os.getenv("HOME"));
43         end
44 end
45
46 -- Global 'prosody' object
47 local prosody = {
48         hosts = {};
49         events = require "util.events".new();
50         platform = "posix";
51         lock_globals = function () end;
52         unlock_globals = function () end;
53         installed = CFG_SOURCEDIR ~= nil;
54         core_post_stanza = function () end; -- TODO: mod_router!
55 };
56 _G.prosody = prosody;
57
58 local dependencies = require "util.dependencies";
59 if not dependencies.check_dependencies() then
60         os.exit(1);
61 end
62
63 config = require "core.configmanager"
64
65 local ENV_CONFIG;
66 do
67         local filenames = {};
68         
69         local filename;
70         if arg[1] == "--config" and arg[2] then
71                 table.insert(filenames, arg[2]);
72                 if CFG_CONFIGDIR then
73                         table.insert(filenames, CFG_CONFIGDIR.."/"..arg[2]);
74                 end
75                 table.remove(arg, 1); table.remove(arg, 1);
76         else
77                 for _, format in ipairs(config.parsers()) do
78                         table.insert(filenames, (CFG_CONFIGDIR or ".").."/prosody.cfg."..format);
79                 end
80         end
81         for _,_filename in ipairs(filenames) do
82                 filename = _filename;
83                 local file = io.open(filename);
84                 if file then
85                         file:close();
86                         ENV_CONFIG = filename;
87                         CFG_CONFIGDIR = filename:match("^(.*)[\\/][^\\/]*$");
88                         break;
89                 end
90         end
91         local ok, level, err = config.load(filename);
92         if not ok then
93                 print("\n");
94                 print("**************************");
95                 if level == "parser" then
96                         print("A problem occured while reading the config file "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
97                         local err_line, err_message = tostring(err):match("%[string .-%]:(%d*): (.*)");
98                         print("Error"..(err_line and (" on line "..err_line) or "")..": "..(err_message or tostring(err)));
99                         print("");
100                 elseif level == "file" then
101                         print("Prosody was unable to find the configuration file.");
102                         print("We looked for: "..(CFG_CONFIGDIR or ".").."/prosody.cfg.lua");
103                         print("A sample config file is included in the Prosody download called prosody.cfg.lua.dist");
104                         print("Copy or rename it to prosody.cfg.lua and edit as necessary.");
105                 end
106                 print("More help on configuring Prosody can be found at http://prosody.im/doc/configure");
107                 print("Good luck!");
108                 print("**************************");
109                 print("");
110                 os.exit(1);
111         end
112 end
113 local original_logging_config = config.get("*", "log");
114 config.set("*", "log", { { levels = { min="info" }, to = "console" } });
115
116 local data_path = config.get("*", "data_path") or CFG_DATADIR or "data";
117 local custom_plugin_paths = config.get("*", "plugin_paths");
118 if custom_plugin_paths then
119         local path_sep = package.config:sub(3,3);
120         -- path1;path2;path3;defaultpath...
121         CFG_PLUGINDIR = table.concat(custom_plugin_paths, path_sep)..path_sep..(CFG_PLUGINDIR or "plugins");
122 end
123 prosody.paths = { source = CFG_SOURCEDIR, config = CFG_CONFIGDIR, 
124                   plugins = CFG_PLUGINDIR or "plugins", data = data_path };
125
126 if prosody.installed then
127         -- Change working directory to data path.
128         require "lfs".chdir(data_path);
129 end
130
131 require "core.loggingmanager"
132
133 dependencies.log_warnings();
134
135 -- Switch away from root and into the prosody user --
136 local switched_user, current_uid;
137
138 local want_pposix_version = "0.3.6";
139 local ok, pposix = pcall(require, "util.pposix");
140
141 if ok and pposix then
142         if pposix._VERSION ~= want_pposix_version then print(string.format("Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version)); return; end
143         current_uid = pposix.getuid();
144         if current_uid == 0 then
145                 -- We haz root!
146                 local desired_user = config.get("*", "prosody_user") or "prosody";
147                 local desired_group = config.get("*", "prosody_group") or desired_user;
148                 local ok, err = pposix.setgid(desired_group);
149                 if ok then
150                         ok, err = pposix.initgroups(desired_user);
151                 end
152                 if ok then
153                         ok, err = pposix.setuid(desired_user);
154                         if ok then
155                                 -- Yay!
156                                 switched_user = true;
157                         end
158                 end
159                 if not switched_user then
160                         -- Boo!
161                         print("Warning: Couldn't switch to Prosody user/group '"..tostring(desired_user).."'/'"..tostring(desired_group).."': "..tostring(err));
162                 end
163         end
164         
165         -- Set our umask to protect data files
166         pposix.umask(config.get("*", "umask") or "027");
167         pposix.setenv("HOME", data_path);
168         pposix.setenv("PROSODY_CONFIG", ENV_CONFIG);
169 else
170         print("Error: Unable to load pposix module. Check that Prosody is installed correctly.")
171         print("For more help send the below error to us through http://prosody.im/discuss");
172         print(tostring(pposix))
173         os.exit(1);
174 end
175
176 local function test_writeable(filename)
177         local f, err = io.open(filename, "a");
178         if not f then
179                 return false, err;
180         end
181         f:close();
182         return true;
183 end
184
185 local unwriteable_files = {};
186 if type(original_logging_config) == "string" and original_logging_config:sub(1,1) ~= "*" then
187         local ok, err = test_writeable(original_logging_config);
188         if not ok then
189                 table.insert(unwriteable_files, err);
190         end
191 elseif type(original_logging_config) == "table" then
192         for _, rule in ipairs(original_logging_config) do
193                 if rule.filename then
194                         local ok, err = test_writeable(rule.filename);
195                         if not ok then
196                                 table.insert(unwriteable_files, err);
197                         end
198                 end
199         end
200 end
201
202 if #unwriteable_files > 0 then
203         print("One of more of the Prosody log files are not");
204         print("writeable, please correct the errors and try");
205         print("starting prosodyctl again.");
206         print("");
207         for _, err in ipairs(unwriteable_files) do
208                 print(err);
209         end
210         print("");
211         os.exit(1);
212 end
213
214
215 local error_messages = setmetatable({ 
216                 ["invalid-username"] = "The given username is invalid in a Jabber ID";
217                 ["invalid-hostname"] = "The given hostname is invalid";
218                 ["no-password"] = "No password was supplied";
219                 ["no-such-user"] = "The given user does not exist on the server";
220                 ["no-such-host"] = "The given hostname does not exist in the config";
221                 ["unable-to-save-data"] = "Unable to store, perhaps you don't have permission?";
222                 ["no-pidfile"] = "There is no 'pidfile' option in the configuration file, see http://prosody.im/doc/prosodyctl#pidfile for help";
223                 ["no-posix"] = "The mod_posix module is not enabled in the Prosody config file, see http://prosody.im/doc/prosodyctl for more info";
224                 ["no-such-method"] = "This module has no commands";
225                 ["not-running"] = "Prosody is not running";
226                 }, { __index = function (t,k) return "Error: "..(tostring(k):gsub("%-", " "):gsub("^.", string.upper)); end });
227
228 hosts = prosody.hosts;
229
230 local function make_host(hostname)
231         return {
232                 type = "local",
233                 events = prosody.events,
234                 modules = {},
235                 users = require "core.usermanager".new_null_provider(hostname)
236         };
237 end
238
239 for hostname, config in pairs(config.getconfig()) do
240         hosts[hostname] = make_host(hostname);
241 end
242         
243 local modulemanager = require "core.modulemanager"
244
245 local prosodyctl = require "util.prosodyctl"
246 require "socket"
247 -----------------------
248
249  -- FIXME: Duplicate code waiting for util.startup
250 function read_version()
251         -- Try to determine version
252         local version_file = io.open((CFG_SOURCEDIR or ".").."/prosody.version");
253         if version_file then
254                 prosody.version = version_file:read("*a"):gsub("%s*$", "");
255                 version_file:close();
256                 if #prosody.version == 12 and prosody.version:match("^[a-f0-9]+$") then
257                         prosody.version = "hg:"..prosody.version;
258                 end
259         else
260                 prosody.version = "unknown";
261         end
262 end
263
264 local show_message, show_warning = prosodyctl.show_message, prosodyctl.show_warning;
265 local show_usage = prosodyctl.show_usage;
266 local getchar, getpass = prosodyctl.getchar, prosodyctl.getpass;
267 local show_yesno = prosodyctl.show_yesno;
268 local show_prompt = prosodyctl.show_prompt;
269 local read_password = prosodyctl.read_password;
270
271 local jid_split = require "util.jid".prepped_split;
272
273 local prosodyctl_timeout = (config.get("*", "prosodyctl_timeout") or 5) * 2;
274 -----------------------
275 local commands = {};
276 local command = arg[1];
277
278 function commands.adduser(arg)
279         if not arg[1] or arg[1] == "--help" then
280                 show_usage([[adduser JID]], [[Create the specified user account in Prosody]]);
281                 return 1;
282         end
283         local user, host = jid_split(arg[1]);
284         if not user and host then
285                 show_message [[Failed to understand JID, please supply the JID you want to create]]
286                 show_usage [[adduser user@host]]
287                 return 1;
288         end
289         
290         if not host then
291                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
292                 return 1;
293         end
294         
295         if not hosts[host] then
296                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
297                 show_warning("The user will not be able to log in until this is changed.");
298                 hosts[host] = make_host(host);
299         end
300         
301         if prosodyctl.user_exists{ user = user, host = host } then
302                 show_message [[That user already exists]];
303                 return 1;
304         end
305         
306         local password = read_password();
307         if not password then return 1; end
308         
309         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
310         
311         if ok then return 0; end
312         
313         show_message(msg)
314         return 1;
315 end
316
317 function commands.passwd(arg)
318         if not arg[1] or arg[1] == "--help" then
319                 show_usage([[passwd JID]], [[Set the password for the specified user account in Prosody]]);
320                 return 1;
321         end
322         local user, host = jid_split(arg[1]);
323         if not user and host then
324                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
325                 show_usage [[passwd user@host]]
326                 return 1;
327         end
328         
329         if not host then
330                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
331                 return 1;
332         end
333         
334         if not hosts[host] then
335                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
336                 show_warning("The user will not be able to log in until this is changed.");
337                 hosts[host] = make_host(host);
338         end
339         
340         if not prosodyctl.user_exists { user = user, host = host } then
341                 show_message [[That user does not exist, use prosodyctl adduser to create a new user]]
342                 return 1;
343         end
344         
345         local password = read_password();
346         if not password then return 1; end
347         
348         local ok, msg = prosodyctl.passwd { user = user, host = host, password = password };
349         
350         if ok then return 0; end
351         
352         show_message(error_messages[msg])
353         return 1;
354 end
355
356 function commands.deluser(arg)
357         if not arg[1] or arg[1] == "--help" then
358                 show_usage([[deluser JID]], [[Permanently remove the specified user account from Prosody]]);
359                 return 1;
360         end
361         local user, host = jid_split(arg[1]);
362         if not user and host then
363                 show_message [[Failed to understand JID, please supply the JID you want to set the password for]]
364                 show_usage [[passwd user@host]]
365                 return 1;
366         end
367         
368         if not host then
369                 show_message [[Please specify a JID, including a host. e.g. alice@example.com]];
370                 return 1;
371         end
372         
373         if not hosts[host] then
374                 show_warning("The host '%s' is not listed in the configuration file (or is not enabled).", host)
375                 hosts[host] = make_host(host);
376         end
377
378         if not prosodyctl.user_exists { user = user, host = host } then
379                 show_message [[That user does not exist on this server]]
380                 return 1;
381         end
382         
383         local ok, msg = prosodyctl.deluser { user = user, host = host };
384         
385         if ok then return 0; end
386         
387         show_message(error_messages[msg])
388         return 1;
389 end
390
391 function commands.start(arg)
392         if arg[1] == "--help" then
393                 show_usage([[start]], [[Start Prosody]]);
394                 return 1;
395         end
396         local ok, ret = prosodyctl.isrunning();
397         if not ok then
398                 show_message(error_messages[ret]);
399                 return 1;
400         end
401         
402         if ret then
403                 local ok, ret = prosodyctl.getpid();
404                 if not ok then
405                         show_message("Couldn't get running Prosody's PID");
406                         show_message(error_messages[ret]);
407                         return 1;
408                 end
409                 show_message("Prosody is already running with PID %s", ret or "(unknown)");
410                 return 1;
411         end
412         
413         local ok, ret = prosodyctl.start();
414         if ok then
415                 local daemonize = config.get("*", "daemonize");
416                 if daemonize == nil then
417                         daemonize = prosody.installed;
418                 end
419                 if daemonize then
420                         local i=1;
421                         while true do
422                                 local ok, running = prosodyctl.isrunning();
423                                 if ok and running then
424                                         break;
425                                 elseif i == 5 then
426                                         show_message("Still waiting...");
427                                 elseif i >= prosodyctl_timeout then
428                                         show_message("Prosody is still not running. Please give it some time or check your log files for errors.");
429                                         return 2;
430                                 end
431                                 socket.sleep(0.5);
432                                 i = i + 1;
433                         end
434                         show_message("Started");
435                 end
436                 return 0;
437         end
438
439         show_message("Failed to start Prosody");
440         show_message(error_messages[ret])       
441         return 1;       
442 end
443
444 function commands.status(arg)
445         if arg[1] == "--help" then
446                 show_usage([[status]], [[Reports the running status of Prosody]]);
447                 return 1;
448         end
449
450         local ok, ret = prosodyctl.isrunning();
451         if not ok then
452                 show_message(error_messages[ret]);
453                 return 1;
454         end
455         
456         if ret then
457                 local ok, ret = prosodyctl.getpid();
458                 if not ok then
459                         show_message("Couldn't get running Prosody's PID");
460                         show_message(error_messages[ret]);
461                         return 1;
462                 end
463                 show_message("Prosody is running with PID %s", ret or "(unknown)");
464                 return 0;
465         else
466                 show_message("Prosody is not running");
467                 if not switched_user and current_uid ~= 0 then
468                         print("\nNote:")
469                         print(" You will also see this if prosodyctl is not running under");
470                         print(" the same user account as Prosody. Try running as root (e.g. ");
471                         print(" with 'sudo' in front) to gain access to Prosody's real status.");
472                 end
473                 return 2
474         end
475         return 1;
476 end
477
478 function commands.stop(arg)
479         if arg[1] == "--help" then
480                 show_usage([[stop]], [[Stop a running Prosody server]]);
481                 return 1;
482         end
483
484         if not prosodyctl.isrunning() then
485                 show_message("Prosody is not running");
486                 return 1;
487         end
488         
489         local ok, ret = prosodyctl.stop();
490         if ok then
491                 local i=1;
492                 while true do
493                         local ok, running = prosodyctl.isrunning();
494                         if ok and not running then
495                                 break;
496                         elseif i == 5 then
497                                 show_message("Still waiting...");
498                         elseif i >= prosodyctl_timeout then
499                                 show_message("Prosody is still running. Please give it some time or check your log files for errors.");
500                                 return 2;
501                         end
502                         socket.sleep(0.5);
503                         i = i + 1;
504                 end
505                 show_message("Stopped");
506                 return 0;
507         end
508
509         show_message(error_messages[ret]);
510         return 1;
511 end
512
513 function commands.restart(arg)
514         if arg[1] == "--help" then
515                 show_usage([[restart]], [[Restart a running Prosody server]]);
516                 return 1;
517         end
518         
519         commands.stop(arg);
520         return commands.start(arg);
521 end
522
523 function commands.about(arg)
524         read_version();
525         if arg[1] == "--help" then
526                 show_usage([[about]], [[Show information about this Prosody installation]]);
527                 return 1;
528         end
529         
530         local array = require "util.array";
531         local keys = require "util.iterators".keys;
532         
533         print("Prosody "..(prosody.version or "(unknown version)"));
534         print("");
535         print("# Prosody directories");
536         print("Data directory:  ", CFG_DATADIR or "./");
537         print("Plugin directory:", CFG_PLUGINDIR or "./");
538         print("Config directory:", CFG_CONFIGDIR or "./");
539         print("Source directory:", CFG_SOURCEDIR or "./");
540         print("");
541         print("# Lua environment");
542         print("Lua version:             ", _G._VERSION);
543         print("");
544         print("Lua module search paths:");
545         for path in package.path:gmatch("[^;]+") do
546                 print("  "..path);
547         end
548         print("");
549         print("Lua C module search paths:");
550         for path in package.cpath:gmatch("[^;]+") do
551                 print("  "..path);
552         end
553         print("");
554         local luarocks_status = (pcall(require, "luarocks.loader") and "Installed ("..(luarocks.cfg.program_version or "2.x+")..")")
555                 or (pcall(require, "luarocks.require") and "Installed (1.x)")
556                 or "Not installed";
557         print("LuaRocks:        ", luarocks_status);
558         print("");
559         print("# Lua module versions");
560         local module_versions, longest_name = {}, 8;
561         for name, module in pairs(package.loaded) do
562                 if type(module) == "table" and rawget(module, "_VERSION")
563                 and name ~= "_G" and not name:match("%.") then
564                         if #name > longest_name then
565                                 longest_name = #name;
566                         end
567                         module_versions[name] = module._VERSION;
568                 end
569         end
570         local sorted_keys = array.collect(keys(module_versions)):sort();
571         for _, name in ipairs(array.collect(keys(module_versions)):sort()) do
572                 print(name..":"..string.rep(" ", longest_name-#name), module_versions[name]);
573         end
574         print("");
575 end
576
577 function commands.reload(arg)
578         if arg[1] == "--help" then
579                 show_usage([[reload]], [[Reload Prosody's configuration and re-open log files]]);
580                 return 1;
581         end
582
583         if not prosodyctl.isrunning() then
584                 show_message("Prosody is not running");
585                 return 1;
586         end
587         
588         local ok, ret = prosodyctl.reload();
589         if ok then
590                 
591                 show_message("Prosody log files re-opened and config file reloaded. You may need to reload modules for some changes to take effect.");
592                 return 0;
593         end
594
595         show_message(error_messages[ret]);
596         return 1;
597 end
598 -- ejabberdctl compatibility
599
600 function commands.register(arg)
601         local user, host, password = unpack(arg);
602         if (not (user and host)) or arg[1] == "--help" then
603                 if user ~= "--help" then
604                         if not user then
605                                 show_message [[No username specified]]
606                         elseif not host then
607                                 show_message [[Please specify which host you want to register the user on]];
608                         end
609                 end
610                 show_usage("register USER HOST [PASSWORD]", "Register a user on the server, with the given password");
611                 return 1;
612         end
613         if not password then
614                 password = read_password();
615                 if not password then
616                         show_message [[Unable to register user with no password]];
617                         return 1;
618                 end
619         end
620         
621         local ok, msg = prosodyctl.adduser { user = user, host = host, password = password };
622         
623         if ok then return 0; end
624         
625         show_message(error_messages[msg])
626         return 1;
627 end
628
629 function commands.unregister(arg)
630         local user, host = unpack(arg);
631         if (not (user and host)) or arg[1] == "--help" then
632                 if user ~= "--help" then
633                         if not user then
634                                 show_message [[No username specified]]
635                         elseif not host then
636                                 show_message [[Please specify which host you want to unregister the user from]];
637                         end
638                 end
639                 show_usage("unregister USER HOST [PASSWORD]", "Permanently remove a user account from the server");
640                 return 1;
641         end
642
643         local ok, msg = prosodyctl.deluser { user = user, host = host };
644         
645         if ok then return 0; end
646         
647         show_message(error_messages[msg])
648         return 1;
649 end
650
651 local openssl;
652 local lfs;
653
654 local cert_commands = {};
655
656 local function ask_overwrite(filename)
657         return lfs.attributes(filename) and not show_yesno("Overwrite "..filename .. "?");
658 end
659
660 function cert_commands.config(arg)
661         if #arg >= 1 and arg[1] ~= "--help" then
662                 local conf_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".cnf";
663                 if ask_overwrite(conf_filename) then
664                         return nil, conf_filename;
665                 end
666                 local conf = openssl.config.new();
667                 conf:from_prosody(hosts, config, arg);
668                 show_message("Please provide details to include in the certificate config file.");
669                 show_message("Leave the field empty to use the default value or '.' to exclude the field.")
670                 for i, k in ipairs(openssl._DN_order) do
671                         local v = conf.distinguished_name[k];
672                         if v then
673                                 local nv;
674                                 if k == "commonName" then
675                                         v = arg[1]
676                                 elseif k == "emailAddress" then
677                                         v = "xmpp@" .. arg[1];
678                                 elseif k == "countryName" then
679                                         local tld = arg[1]:match"%.([a-z]+)$";
680                                         if tld and #tld == 2 and tld ~= "uk" then
681                                                 v = tld:upper();
682                                         end
683                                 end
684                                 nv = show_prompt(("%s (%s):"):format(k, nv or v));
685                                 nv = (not nv or nv == "") and v or nv;
686                                 if nv:find"[\192-\252][\128-\191]+" then
687                                         conf.req.string_mask = "utf8only"
688                                 end
689                                 conf.distinguished_name[k] = nv ~= "." and nv or nil;
690                         end
691                 end
692                 local conf_file, err = io.open(conf_filename, "w");
693                 if not conf_file then
694                         show_warning("Could not open OpenSSL config file for writing");
695                         show_warning(err);
696                         os.exit(1);
697                 end
698                 conf_file:write(conf:serialize());
699                 conf_file:close();
700                 print("");
701                 show_message("Config written to " .. conf_filename);
702                 return nil, conf_filename;
703         else
704                 show_usage("cert config HOSTNAME [HOSTNAME+]", "Builds a certificate config file covering the supplied hostname(s)")
705         end
706 end
707
708 function cert_commands.key(arg)
709         if #arg >= 1 and arg[1] ~= "--help" then
710                 local key_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".key";
711                 if ask_overwrite(key_filename) then
712                         return nil, key_filename;
713                 end
714                 os.remove(key_filename); -- This file, if it exists is unlikely to have write permissions
715                 local key_size = tonumber(arg[2] or show_prompt("Choose key size (2048):") or 2048);
716                 local old_umask = pposix.umask("0377");
717                 if openssl.genrsa{out=key_filename, key_size} then
718                         os.execute(("chmod 400 '%s'"):format(key_filename));
719                         show_message("Key written to ".. key_filename);
720                         pposix.umask(old_umask);
721                         return nil, key_filename;
722                 end
723                 show_message("There was a problem, see OpenSSL output");
724         else
725                 show_usage("cert key HOSTNAME <bits>", "Generates a RSA key named HOSTNAME.key\n "
726                 .."Prompts for a key size if none given")
727         end
728 end
729
730 function cert_commands.request(arg)
731         if #arg >= 1 and arg[1] ~= "--help" then
732                 local req_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".req";
733                 if ask_overwrite(req_filename) then
734                         return nil, req_filename;
735                 end
736                 local _, key_filename = cert_commands.key({arg[1]});
737                 local _, conf_filename = cert_commands.config(arg);
738                 if openssl.req{new=true, key=key_filename, utf8=true, config=conf_filename, out=req_filename} then
739                         show_message("Certificate request written to ".. req_filename);
740                 else
741                         show_message("There was a problem, see OpenSSL output");
742                 end
743         else
744                 show_usage("cert request HOSTNAME [HOSTNAME+]", "Generates a certificate request for the supplied hostname(s)")
745         end
746 end
747
748 function cert_commands.generate(arg)
749         if #arg >= 1 and arg[1] ~= "--help" then
750                 local cert_filename = (CFG_DATADIR or "./certs") .. "/" .. arg[1] .. ".crt";
751                 if ask_overwrite(cert_filename) then
752                         return nil, cert_filename;
753                 end
754                 local _, key_filename = cert_commands.key({arg[1]});
755                 local _, conf_filename = cert_commands.config(arg);
756                 local ret;
757                 if key_filename and conf_filename and cert_filename
758                         and openssl.req{new=true, x509=true, nodes=true, key=key_filename,
759                                 days=365, sha1=true, utf8=true, config=conf_filename, out=cert_filename} then
760                         show_message("Certificate written to ".. cert_filename);
761                 else
762                         show_message("There was a problem, see OpenSSL output");
763                 end
764         else
765                 show_usage("cert generate HOSTNAME [HOSTNAME+]", "Generates a self-signed certificate for the current hostname(s)")
766         end
767 end
768
769 function commands.cert(arg)
770         if #arg >= 1 and arg[1] ~= "--help" then
771                 openssl = require "util.openssl";
772                 lfs = require "lfs";
773                 local subcmd = table.remove(arg, 1);
774                 if type(cert_commands[subcmd]) == "function" then
775                         if not arg[1] then
776                                 show_message"You need to supply at least one hostname"
777                                 arg = { "--help" };
778                         end
779                         if arg[1] ~= "--help" and not hosts[arg[1]] then
780                                 show_message(error_messages["no-such-host"]);
781                                 return
782                         end
783                         return cert_commands[subcmd](arg);
784                 end
785         end
786         show_usage("cert config|request|generate|key", "Helpers for generating X.509 certificates and keys.")
787 end
788
789 function commands.check(arg)
790         if arg[1] == "--help" then
791                 show_usage([[check]], [[Perform basic checks on your Prosody installation]]);
792                 return 1;
793         end
794         local what = table.remove(arg, 1);
795         local array, set = require "util.array", require "util.set";
796         local it = require "util.iterators";
797         local ok = true;
798         local function disabled_hosts(host, conf) return host ~= "*" and conf.enabled ~= false; end
799         local function enabled_hosts() return it.filter(disabled_hosts, pairs(config.getconfig())); end
800         if not what or what == "disabled" then
801                 local disabled_hosts = set.new();
802                 for host, host_options in it.filter("*", pairs(config.getconfig())) do
803                         if host_options.enabled == false then
804                                 disabled_hosts:add(host);
805                         end
806                 end
807                 if not disabled_hosts:empty() then
808                         local msg = "Checks will be skipped for these disabled hosts: %s";
809                         if what then msg = "These hosts are disabled: %s"; end
810                         show_warning(msg, tostring(disabled_hosts));
811                         if what then return 0; end
812                         print""
813                 end
814         end
815         if not what or what == "config" then
816                 print("Checking config...");
817                 local deprecated = set.new({
818                         "bosh_ports", "disallow_s2s", "no_daemonize", "anonymous_login",
819                 });
820                 local known_global_options = set.new({
821                         "pidfile", "log", "plugin_paths", "prosody_user", "prosody_group", "daemonize",
822                         "umask", "prosodyctl_timeout", "use_ipv6", "use_libevent", "network_settings"
823                 });
824                 local config = config.getconfig();
825                 -- Check that we have any global options (caused by putting a host at the top)
826                 if it.count(it.filter("log", pairs(config["*"]))) == 0 then
827                         ok = false;
828                         print("");
829                         print("    No global options defined. Perhaps you have put a host definition at the top")
830                         print("    of the config file? They should be at the bottom, see http://prosody.im/doc/configure#overview");
831                 end
832                 if it.count(enabled_hosts()) == 0 then
833                         ok = false;
834                         print("");
835                         if it.count(it.filter("*", pairs(config))) == 0 then
836                                 print("    No hosts are defined, please add at least one VirtualHost section")
837                         elseif config["*"]["enabled"] == false then
838                                 print("    No hosts are enabled. Remove enabled = false from the global section or put enabled = true under at least one VirtualHost section")
839                         else
840                                 print("    All hosts are disabled. Remove enabled = false from at least one VirtualHost section")
841                         end
842                 end
843                 -- Check for global options under hosts
844                 local global_options = set.new(it.to_array(it.keys(config["*"])));
845                 local deprecated_global_options = set.intersection(global_options, deprecated);
846                 if not deprecated_global_options:empty() then
847                         print("");
848                         print("    You have some deprecated options in the global section:");
849                         print("    "..tostring(deprecated_global_options))
850                         ok = false;
851                 end
852                 for host, options in enabled_hosts() do
853                         local host_options = set.new(it.to_array(it.keys(options)));
854                         local misplaced_options = set.intersection(host_options, known_global_options);
855                         for name in pairs(options) do
856                                 if name:match("^interfaces?")
857                                 or name:match("_ports?$") or name:match("_interfaces?$")
858                                 or name:match("_ssl$") then
859                                         misplaced_options:add(name);
860                                 end
861                         end
862                         if not misplaced_options:empty() then
863                                 ok = false;
864                                 print("");
865                                 local n = it.count(misplaced_options);
866                                 print("    You have "..n.." option"..(n>1 and "s " or " ").."set under "..host.." that should be");
867                                 print("    in the global section of the config file, above any VirtualHost or Component definitions,")
868                                 print("    see http://prosody.im/doc/configure#overview for more information.")
869                                 print("");
870                                 print("    You need to move the following option"..(n>1 and "s" or "")..": "..table.concat(it.to_array(misplaced_options), ", "));
871                         end
872                         local subdomain = host:match("^[^.]+");
873                         if not(host_options:contains("component_module")) and (subdomain == "jabber" or subdomain == "xmpp"
874                            or subdomain == "chat" or subdomain == "im") then
875                                 print("");
876                                 print("    Suggestion: If "..host.. " is a new host with no real users yet, consider renaming it now to");
877                                 print("     "..host:gsub("^[^.]+%.", "")..". You can use SRV records to redirect XMPP clients and servers to "..host..".");
878                                 print("     For more information see: http://prosody.im/doc/dns");
879                         end
880                 end
881                 
882                 print("Done.\n");
883         end
884         if not what or what == "dns" then
885                 local dns = require "net.dns";
886                 local idna = require "util.encodings".idna;
887                 local ip = require "util.ip";
888                 local c2s_ports = set.new(config.get("*", "c2s_ports") or {5222});
889                 local s2s_ports = set.new(config.get("*", "s2s_ports") or {5269});
890                 
891                 local c2s_srv_required, s2s_srv_required;
892                 if not c2s_ports:contains(5222) then
893                         c2s_srv_required = true;
894                 end
895                 if not s2s_ports:contains(5269) then
896                         s2s_srv_required = true;
897                 end
898                 
899                 local problem_hosts = set.new();
900                 
901                 local external_addresses, internal_addresses = set.new(), set.new();
902                 
903                 local fqdn = socket.dns.tohostname(socket.dns.gethostname());
904                 if fqdn then
905                         local res = dns.lookup(idna.to_ascii(fqdn), "A");
906                         if res then
907                                 for _, record in ipairs(res) do
908                                         external_addresses:add(record.a);
909                                 end
910                         end
911                         local res = dns.lookup(idna.to_ascii(fqdn), "AAAA");
912                         if res then
913                                 for _, record in ipairs(res) do
914                                         external_addresses:add(record.aaaa);
915                                 end
916                         end
917                 end
918                 
919                 local local_addresses = require"util.net".local_addresses() or {};
920                 
921                 for addr in it.values(local_addresses) do
922                         if not ip.new_ip(addr).private then
923                                 external_addresses:add(addr);
924                         else
925                                 internal_addresses:add(addr);
926                         end
927                 end
928                 
929                 if external_addresses:empty() then
930                         print("");
931                         print("   Failed to determine the external addresses of this server. Checks may be inaccurate.");
932                         c2s_srv_required, s2s_srv_required = true, true;
933                 end
934                 
935                 local v6_supported = not not socket.tcp6;
936                 
937                 for host, host_options in enabled_hosts() do
938                         local all_targets_ok, some_targets_ok = true, false;
939                         
940                         local is_component = not not host_options.component_module;
941                         print("Checking DNS for "..(is_component and "component" or "host").." "..host.."...");
942                         local target_hosts = set.new();
943                         if not is_component then
944                                 local res = dns.lookup("_xmpp-client._tcp."..idna.to_ascii(host)..".", "SRV");
945                                 if res then
946                                         for _, record in ipairs(res) do
947                                                 target_hosts:add(record.srv.target);
948                                                 if not c2s_ports:contains(record.srv.port) then
949                                                         print("    SRV target "..record.srv.target.." contains unknown client port: "..record.srv.port);
950                                                 end
951                                         end
952                                 else
953                                         if c2s_srv_required then
954                                                 print("    No _xmpp-client SRV record found for "..host..", but it looks like you need one.");
955                                                 all_targst_ok = false;
956                                         else
957                                                 target_hosts:add(host);
958                                         end
959                                 end
960                         end
961                         local res = dns.lookup("_xmpp-server._tcp."..idna.to_ascii(host)..".", "SRV");
962                         if res then
963                                 for _, record in ipairs(res) do
964                                         target_hosts:add(record.srv.target);
965                                         if not s2s_ports:contains(record.srv.port) then
966                                                 print("    SRV target "..record.srv.target.." contains unknown server port: "..record.srv.port);
967                                         end
968                                 end
969                         else
970                                 if s2s_srv_required then
971                                         print("    No _xmpp-server SRV record found for "..host..", but it looks like you need one.");
972                                         all_targets_ok = false;
973                                 else
974                                         target_hosts:add(host);
975                                 end
976                         end
977                         if target_hosts:empty() then
978                                 target_hosts:add(host);
979                         end
980                         
981                         if target_hosts:contains("localhost") then
982                                 print("    Target 'localhost' cannot be accessed from other servers");
983                                 target_hosts:remove("localhost");
984                         end
985                         
986                         local modules = set.new(it.to_array(it.values(host_options.modules_enabled)))
987                                         + set.new(it.to_array(it.values(config.get("*", "modules_enabled"))))
988                                         + set.new({ config.get(host, "component_module") });
989
990                         if modules:contains("proxy65") then
991                                 local proxy65_target = config.get(host, "proxy65_address") or host;
992                                 local A, AAAA = dns.lookup(idna.to_ascii(proxy65_target), "A"), dns.lookup(idna.to_ascii(proxy65_target), "AAAA");
993                                 local prob = {};
994                                 if not A then
995                                         table.insert(prob, "A");
996                                 end
997                                 if v6_supported and not AAAA then
998                                         table.insert(prob, "AAAA");
999                                 end
1000                                 if #prob > 0 then
1001                                         print("    File transfer proxy "..proxy65_target.." has no "..table.concat(prob, "/").." record. Create one or set 'proxy65_address' to the correct host/IP.");
1002                                 end
1003                         end
1004                         
1005                         for host in target_hosts do
1006                                 local host_ok_v4, host_ok_v6;
1007                                 local res = dns.lookup(idna.to_ascii(host), "A");
1008                                 if res then
1009                                         for _, record in ipairs(res) do
1010                                                 if external_addresses:contains(record.a) then
1011                                                         some_targets_ok = true;
1012                                                         host_ok_v4 = true;
1013                                                 elseif internal_addresses:contains(record.a) then
1014                                                         host_ok_v4 = true;
1015                                                         some_targets_ok = true;
1016                                                         print("    "..host.." A record points to internal address, external connections might fail");
1017                                                 else
1018                                                         print("    "..host.." A record points to unknown address "..record.a);
1019                                                         all_targets_ok = false;
1020                                                 end
1021                                         end
1022                                 end
1023                                 local res = dns.lookup(idna.to_ascii(host), "AAAA");
1024                                 if res then
1025                                         for _, record in ipairs(res) do
1026                                                 if external_addresses:contains(record.aaaa) then
1027                                                         some_targets_ok = true;
1028                                                         host_ok_v6 = true;
1029                                                 elseif internal_addresses:contains(record.aaaa) then
1030                                                         host_ok_v6 = true;
1031                                                         some_targets_ok = true;
1032                                                         print("    "..host.." AAAA record points to internal address, external connections might fail");
1033                                                 else
1034                                                         print("    "..host.." AAAA record points to unknown address "..record.aaaa);
1035                                                         all_targets_ok = false;
1036                                                 end
1037                                         end
1038                                 end
1039                                 
1040                                 local bad_protos = {}
1041                                 if not host_ok_v4 then
1042                                         table.insert(bad_protos, "IPv4");
1043                                 end
1044                                 if not host_ok_v6 then
1045                                         table.insert(bad_protos, "IPv6");
1046                                 end
1047                                 if #bad_protos > 0 then
1048                                         print("    Host "..host.." does not seem to resolve to this server ("..table.concat(bad_protos, "/")..")");
1049                                 end
1050                                 if host_ok_v6 and not v6_supported then
1051                                         print("    Host "..host.." has AAAA records, but your version of LuaSocket does not support IPv6.");
1052                                         print("      Please see http://prosody.im/doc/ipv6 for more information.");
1053                                 end
1054                         end
1055                         if not all_targets_ok then
1056                                 print("    "..(some_targets_ok and "Only some" or "No").." targets for "..host.." appear to resolve to this server.");
1057                                 if is_component then
1058                                         print("    DNS records are necessary if you want users on other servers to access this component.");
1059                                 end
1060                                 problem_hosts:add(host);
1061                         end
1062                         print("");
1063                 end
1064                 if not problem_hosts:empty() then
1065                         print("");
1066                         print("For more information about DNS configuration please see http://prosody.im/doc/dns");
1067                         print("");
1068                         ok = false;
1069                 end
1070         end
1071         if not what or what == "certs" then
1072                 local cert_ok;
1073                 print"Checking certificates..."
1074                 local x509_verify_identity = require"util.x509".verify_identity;
1075                 local ssl = dependencies.softreq"ssl";
1076                 -- local datetime_parse = require"util.datetime".parse_x509;
1077                 local load_cert = ssl and ssl.x509 and ssl.x509.load;
1078                 -- or ssl.cert_from_pem
1079                 if not ssl then
1080                         print("LuaSec not available, can't perform certificate checks")
1081                         if what == "certs" then cert_ok = false end
1082                 elseif not load_cert then
1083                         print("This version of LuaSec (" .. ssl._VERSION .. ") does not support certificate checking");
1084                         cert_ok = false
1085                 else
1086                         for host in enabled_hosts() do
1087                                 print("Checking certificate for "..host);
1088                                 -- First, let's find out what certificate this host uses.
1089                                 local ssl_config = config.rawget(host, "ssl");
1090                                 if not ssl_config then
1091                                         local base_host = host:match("%.(.*)");
1092                                         ssl_config = config.get(base_host, "ssl");
1093                                 end
1094                                 if not ssl_config then
1095                                         print("  No 'ssl' option defined for "..host)
1096                                         cert_ok = false
1097                                 elseif not ssl_config.certificate then
1098                                         print("  No 'certificate' set in ssl option for "..host)
1099                                         cert_ok = false
1100                                 elseif not ssl_config.key then
1101                                         print("  No 'key' set in ssl option for "..host)
1102                                         cert_ok = false
1103                                 else
1104                                         local key, err = io.open(ssl_config.key); -- Permissions check only
1105                                         if not key then
1106                                                 print("    Could not open "..ssl_config.key..": "..err);
1107                                                 cert_ok = false
1108                                         else
1109                                                 key:close();
1110                                         end
1111                                         local cert_fh, err = io.open(ssl_config.certificate); -- Load the file.
1112                                         if not cert_fh then
1113                                                 print("    Could not open "..ssl_config.certificate..": "..err);
1114                                                 cert_ok = false
1115                                         else
1116                                                 print("  Certificate: "..ssl_config.certificate)
1117                                                 local cert = load_cert(cert_fh:read"*a"); cert_fh = cert_fh:close();
1118                                                 if not cert:validat(os.time()) then
1119                                                         print("    Certificate has expired.")
1120                                                         cert_ok = false
1121                                                 end
1122                                                 if config.get(host, "component_module") == nil
1123                                                         and not x509_verify_identity(host, "_xmpp-client", cert) then
1124                                                         print("    Not vaild for client connections to "..host..".")
1125                                                         cert_ok = false
1126                                                 end
1127                                                 if (not (config.get(host, "anonymous_login")
1128                                                         or config.get(host, "authentication") == "anonymous"))
1129                                                         and not x509_verify_identity(host, "_xmpp-client", cert) then
1130                                                         print("    Not vaild for server-to-server connections to "..host..".")
1131                                                         cert_ok = false
1132                                                 end
1133                                         end
1134                                 end
1135                         end
1136                         if cert_ok == false then
1137                                 print("")
1138                                 print("For more information about certificates please see http://prosody.im/doc/certificates");
1139                                 ok = false
1140                         end
1141                 end
1142                 print("")
1143         end
1144         if not ok then
1145                 print("Problems found, see above.");
1146         else
1147                 print("All checks passed, congratulations!");
1148         end
1149         return ok and 0 or 2;
1150 end
1151
1152 ---------------------
1153
1154 if command and command:match("^mod_") then -- Is a command in a module
1155         local module_name = command:match("^mod_(.+)");
1156         local ret, err = modulemanager.load("*", module_name);
1157         if not ret then
1158                 show_message("Failed to load module '"..module_name.."': "..err);
1159                 os.exit(1);
1160         end
1161         
1162         table.remove(arg, 1);
1163         
1164         local module = modulemanager.get_module("*", module_name);
1165         if not module then
1166                 show_message("Failed to load module '"..module_name.."': Unknown error");
1167                 os.exit(1);
1168         end
1169         
1170         if not modulemanager.module_has_method(module, "command") then
1171                 show_message("Fail: mod_"..module_name.." does not support any commands");
1172                 os.exit(1);
1173         end
1174         
1175         local ok, ret = modulemanager.call_module_method(module, "command", arg);
1176         if ok then
1177                 if type(ret) == "number" then
1178                         os.exit(ret);
1179                 elseif type(ret) == "string" then
1180                         show_message(ret);
1181                 end
1182                 os.exit(0); -- :)
1183         else
1184                 show_message("Failed to execute command: "..error_messages[ret]);
1185                 os.exit(1); -- :(
1186         end
1187 end
1188
1189 if not commands[command] then -- Show help for all commands
1190         function show_usage(usage, desc)
1191                 print(" "..usage);
1192                 print("    "..desc);
1193         end
1194
1195         print("prosodyctl - Manage a Prosody server");
1196         print("");
1197         print("Usage: "..arg[0].." COMMAND [OPTIONS]");
1198         print("");
1199         print("Where COMMAND may be one of:\n");
1200
1201         local hidden_commands = require "util.set".new{ "register", "unregister", "addplugin" };
1202         local commands_order = { "adduser", "passwd", "deluser", "start", "stop", "restart", "reload", "about" };
1203
1204         local done = {};
1205
1206         for _, command_name in ipairs(commands_order) do
1207                 local command = commands[command_name];
1208                 if command then
1209                         command{ "--help" };
1210                         print""
1211                         done[command_name] = true;
1212                 end
1213         end
1214
1215         for command_name, command in pairs(commands) do
1216                 if not done[command_name] and not hidden_commands:contains(command_name) then
1217                         command{ "--help" };
1218                         print""
1219                         done[command_name] = true;
1220                 end
1221         end
1222         
1223         
1224         os.exit(0);
1225 end
1226
1227 os.exit(commands[command]({ select(2, unpack(arg)) }));