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