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