mod_admin_telnet: Don't rely on getpeerchain returning an empty list
[prosody.git] / plugins / mod_admin_telnet.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 module:set_global();
10
11 local hostmanager = require "core.hostmanager";
12 local modulemanager = require "core.modulemanager";
13 local s2smanager = require "core.s2smanager";
14 local portmanager = require "core.portmanager";
15
16 local _G = _G;
17
18 local prosody = _G.prosody;
19 local hosts = prosody.hosts;
20 local incoming_s2s = prosody.incoming_s2s;
21
22 local console_listener = { default_port = 5582; default_mode = "*a"; interface = "127.0.0.1" };
23
24 local iterators = require "util.iterators";
25 local keys, values = iterators.keys, iterators.values;
26 local jid = require "util.jid";
27 local jid_bare, jid_split = jid.bare, jid.split;
28 local set, array = require "util.set", require "util.array";
29 local cert_verify_identity = require "util.x509".verify_identity;
30 local envload = require "util.envload".envload;
31 local envloadfile = require "util.envload".envloadfile;
32
33 local commands = module:shared("commands")
34 local def_env = module:shared("env");
35 local default_env_mt = { __index = def_env };
36 local core_post_stanza = prosody.core_post_stanza;
37
38 local function redirect_output(_G, session)
39         local env = setmetatable({ print = session.print }, { __index = function (t, k) return rawget(_G, k); end });
40         env.dofile = function(name)
41                 local f, err = envloadfile(name, env);
42                 if not f then return f, err; end
43                 return f();
44         end;
45         return env;
46 end
47
48 console = {};
49
50 function console:new_session(conn)
51         local w = function(s) conn:write(s:gsub("\n", "\r\n")); end;
52         local session = { conn = conn;
53                         send = function (t) w(tostring(t)); end;
54                         print = function (...)
55                                 local t = {};
56                                 for i=1,select("#", ...) do
57                                         t[i] = tostring(select(i, ...));
58                                 end
59                                 w("| "..table.concat(t, "\t").."\n");
60                         end;
61                         disconnect = function () conn:close(); end;
62                         };
63         session.env = setmetatable({}, default_env_mt);
64         
65         -- Load up environment with helper objects
66         for name, t in pairs(def_env) do
67                 if type(t) == "table" then
68                         session.env[name] = setmetatable({ session = session }, { __index = t });
69                 end
70         end
71         
72         return session;
73 end
74
75 function console:process_line(session, line)
76         local useglobalenv;
77         
78         if line:match("^>") then
79                 line = line:gsub("^>", "");
80                 useglobalenv = true;
81         elseif line == "\004" then
82                 commands["bye"](session, line);
83                 return;
84         else
85                 local command = line:match("^%w+") or line:match("%p");
86                 if commands[command] then
87                         commands[command](session, line);
88                         return;
89                 end
90         end
91         
92         session.env._ = line;
93         
94         local chunkname = "=console";
95         local env = (useglobalenv and redirect_output(_G, session)) or session.env or nil
96         local chunk, err = envload("return "..line, chunkname, env);
97         if not chunk then
98                 chunk, err = envload(line, chunkname, env);
99                 if not chunk then
100                         err = err:gsub("^%[string .-%]:%d+: ", "");
101                         err = err:gsub("^:%d+: ", "");
102                         err = err:gsub("'<eof>'", "the end of the line");
103                         session.print("Sorry, I couldn't understand that... "..err);
104                         return;
105                 end
106         end
107         
108         local ranok, taskok, message = pcall(chunk);
109         
110         if not (ranok or message or useglobalenv) and commands[line:lower()] then
111                 commands[line:lower()](session, line);
112                 return;
113         end
114         
115         if not ranok then
116                 session.print("Fatal error while running command, it did not complete");
117                 session.print("Error: "..taskok);
118                 return;
119         end
120         
121         if not message then
122                 session.print("Result: "..tostring(taskok));
123                 return;
124         elseif (not taskok) and message then
125                 session.print("Command completed with a problem");
126                 session.print("Message: "..tostring(message));
127                 return;
128         end
129         
130         session.print("OK: "..tostring(message));
131 end
132
133 local sessions = {};
134
135 function console_listener.onconnect(conn)
136         -- Handle new connection
137         local session = console:new_session(conn);
138         sessions[conn] = session;
139         printbanner(session);
140         session.send(string.char(0));
141 end
142
143 function console_listener.onincoming(conn, data)
144         local session = sessions[conn];
145
146         local partial = session.partial_data;
147         if partial then
148                 data = partial..data;
149         end
150
151         for line in data:gmatch("[^\n]*[\n\004]") do
152                 if session.closed then return end
153                 console:process_line(session, line);
154                 session.send(string.char(0));
155         end
156         session.partial_data = data:match("[^\n]+$");
157 end
158
159 function console_listener.ondisconnect(conn, err)
160         local session = sessions[conn];
161         if session then
162                 session.disconnect();
163                 sessions[conn] = nil;
164         end
165 end
166
167 -- Console commands --
168 -- These are simple commands, not valid standalone in Lua
169
170 function commands.bye(session)
171         session.print("See you! :)");
172         session.closed = true;
173         session.disconnect();
174 end
175 commands.quit, commands.exit = commands.bye, commands.bye;
176
177 commands["!"] = function (session, data)
178         if data:match("^!!") and session.env._ then
179                 session.print("!> "..session.env._);
180                 return console_listener.onincoming(session.conn, session.env._);
181         end
182         local old, new = data:match("^!(.-[^\\])!(.-)!$");
183         if old and new then
184                 local ok, res = pcall(string.gsub, session.env._, old, new);
185                 if not ok then
186                         session.print(res)
187                         return;
188                 end
189                 session.print("!> "..res);
190                 return console_listener.onincoming(session.conn, res);
191         end
192         session.print("Sorry, not sure what you want");
193 end
194
195
196 function commands.help(session, data)
197         local print = session.print;
198         local section = data:match("^help (%w+)");
199         if not section then
200                 print [[Commands are divided into multiple sections. For help on a particular section, ]]
201                 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
202                 print [[]]
203                 print [[c2s - Commands to manage local client-to-server sessions]]
204                 print [[s2s - Commands to manage sessions between this server and others]]
205                 print [[module - Commands to load/reload/unload modules/plugins]]
206                 print [[host - Commands to activate, deactivate and list virtual hosts]]
207                 print [[user - Commands to create and delete users, and change their passwords]]
208                 print [[server - Uptime, version, shutting down, etc.]]
209                 print [[port - Commands to manage ports the server is listening on]]
210                 print [[dns - Commands to manage and inspect the internal DNS resolver]]
211                 print [[config - Reloading the configuration, etc.]]
212                 print [[console - Help regarding the console itself]]
213         elseif section == "c2s" then
214                 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
215                 print [[c2s:show_insecure() - Show all unencrypted client connections]]
216                 print [[c2s:show_secure() - Show all encrypted client connections]]
217                 print [[c2s:close(jid) - Close all sessions for the specified JID]]
218         elseif section == "s2s" then
219                 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
220                 print [[s2s:close(from, to) - Close a connection from one domain to another]]
221                 print [[s2s:closeall(host) - Close all the incoming/outgoing s2s sessions to specified host]]
222         elseif section == "module" then
223                 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
224                 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
225                 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
226                 print [[module:list(host) - List the modules loaded on the specified host]]
227         elseif section == "host" then
228                 print [[host:activate(hostname) - Activates the specified host]]
229                 print [[host:deactivate(hostname) - Disconnects all clients on this host and deactivates]]
230                 print [[host:list() - List the currently-activated hosts]]
231         elseif section == "user" then
232                 print [[user:create(jid, password) - Create the specified user account]]
233                 print [[user:password(jid, password) - Set the password for the specified user account]]
234                 print [[user:delete(jid) - Permanently remove the specified user account]]
235                 print [[user:list(hostname, pattern) - List users on the specified host, optionally filtering with a pattern]]
236         elseif section == "server" then
237                 print [[server:version() - Show the server's version number]]
238                 print [[server:uptime() - Show how long the server has been running]]
239                 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
240         elseif section == "port" then
241                 print [[port:list() - Lists all network ports prosody currently listens on]]
242                 print [[port:close(port, interface) - Close a port]]
243         elseif section == "dns" then
244                 print [[dns:lookup(name, type, class) - Do a DNS lookup]]
245                 print [[dns:addnameserver(nameserver) - Add a nameserver to the list]]
246                 print [[dns:setnameserver(nameserver) - Replace the list of name servers with the supplied one]]
247                 print [[dns:purge() - Clear the DNS cache]]
248                 print [[dns:cache() - Show cached records]]
249         elseif section == "config" then
250                 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
251         elseif section == "console" then
252                 print [[Hey! Welcome to Prosody's admin console.]]
253                 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
254                 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
255                 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
256                 print [[]]
257                 print [[For now we offer a couple of handy shortcuts:]]
258                 print [[!! - Repeat the last command]]
259                 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
260                 print [[]]
261                 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
262                 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
263                 print [[the running server. Great fun, but be careful not to break anything :)]]
264         end
265         print [[]]
266 end
267
268 -- Session environment --
269 -- Anything in def_env will be accessible within the session as a global variable
270
271 def_env.server = {};
272
273 function def_env.server:insane_reload()
274         prosody.unlock_globals();
275         dofile "prosody"
276         prosody = _G.prosody;
277         return true, "Server reloaded";
278 end
279
280 function def_env.server:version()
281         return true, tostring(prosody.version or "unknown");
282 end
283
284 function def_env.server:uptime()
285         local t = os.time()-prosody.start_time;
286         local seconds = t%60;
287         t = (t - seconds)/60;
288         local minutes = t%60;
289         t = (t - minutes)/60;
290         local hours = t%24;
291         t = (t - hours)/24;
292         local days = t;
293         return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
294                 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
295                 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
296 end
297
298 function def_env.server:shutdown(reason)
299         prosody.shutdown(reason);
300         return true, "Shutdown initiated";
301 end
302
303 def_env.module = {};
304
305 local function get_hosts_set(hosts, module)
306         if type(hosts) == "table" then
307                 if hosts[1] then
308                         return set.new(hosts);
309                 elseif hosts._items then
310                         return hosts;
311                 end
312         elseif type(hosts) == "string" then
313                 return set.new { hosts };
314         elseif hosts == nil then
315                 local mm = require "modulemanager";
316                 local hosts_set = set.new(array.collect(keys(prosody.hosts)))
317                         / function (host) return (prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module)) and host or nil; end;
318                 if module and mm.get_module("*", module) then
319                         hosts_set:add("*");
320                 end
321                 return hosts_set;
322         end
323 end
324
325 function def_env.module:load(name, hosts, config)
326         local mm = require "modulemanager";
327         
328         hosts = get_hosts_set(hosts);
329         
330         -- Load the module for each host
331         local ok, err, count, mod = true, nil, 0, nil;
332         for host in hosts do
333                 if (not mm.is_loaded(host, name)) then
334                         mod, err = mm.load(host, name, config);
335                         if not mod then
336                                 ok = false;
337                                 if err == "global-module-already-loaded" then
338                                         if count > 0 then
339                                                 ok, err, count = true, nil, 1;
340                                         end
341                                         break;
342                                 end
343                                 self.session.print(err or "Unknown error loading module");
344                         else
345                                 count = count + 1;
346                                 self.session.print("Loaded for "..mod.module.host);
347                         end
348                 end
349         end
350         
351         return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));       
352 end
353
354 function def_env.module:unload(name, hosts)
355         local mm = require "modulemanager";
356
357         hosts = get_hosts_set(hosts, name);
358         
359         -- Unload the module for each host
360         local ok, err, count = true, nil, 0;
361         for host in hosts do
362                 if mm.is_loaded(host, name) then
363                         ok, err = mm.unload(host, name);
364                         if not ok then
365                                 ok = false;
366                                 self.session.print(err or "Unknown error unloading module");
367                         else
368                                 count = count + 1;
369                                 self.session.print("Unloaded from "..host);
370                         end
371                 end
372         end
373         return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
374 end
375
376 function def_env.module:reload(name, hosts)
377         local mm = require "modulemanager";
378
379         hosts = array.collect(get_hosts_set(hosts, name)):sort(function (a, b)
380                 if a == "*" then return true
381                 elseif b == "*" then return false
382                 else return a < b; end
383         end);
384
385         -- Reload the module for each host
386         local ok, err, count = true, nil, 0;
387         for _, host in ipairs(hosts) do
388                 if mm.is_loaded(host, name) then
389                         ok, err = mm.reload(host, name);
390                         if not ok then
391                                 ok = false;
392                                 self.session.print(err or "Unknown error reloading module");
393                         else
394                                 count = count + 1;
395                                 if ok == nil then
396                                         ok = true;
397                                 end
398                                 self.session.print("Reloaded on "..host);
399                         end
400                 end
401         end
402         return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
403 end
404
405 function def_env.module:list(hosts)
406         if hosts == nil then
407                 hosts = array.collect(keys(prosody.hosts));
408                 table.insert(hosts, 1, "*");
409         end
410         if type(hosts) == "string" then
411                 hosts = { hosts };
412         end
413         if type(hosts) ~= "table" then
414                 return false, "Please supply a host or a list of hosts you would like to see";
415         end
416         
417         local print = self.session.print;
418         for _, host in ipairs(hosts) do
419                 print((host == "*" and "Global" or host)..":");
420                 local modules = array.collect(keys(modulemanager.get_modules(host) or {})):sort();
421                 if #modules == 0 then
422                         if prosody.hosts[host] then
423                                 print("    No modules loaded");
424                         else
425                                 print("    Host not found");
426                         end
427                 else
428                         for _, name in ipairs(modules) do
429                                 print("    "..name);
430                         end
431                 end
432         end
433 end
434
435 def_env.config = {};
436 function def_env.config:load(filename, format)
437         local config_load = require "core.configmanager".load;
438         local ok, err = config_load(filename, format);
439         if not ok then
440                 return false, err or "Unknown error loading config";
441         end
442         return true, "Config loaded";
443 end
444
445 function def_env.config:get(host, section, key)
446         local config_get = require "core.configmanager".get
447         return true, tostring(config_get(host, section, key));
448 end
449
450 function def_env.config:reload()
451         local ok, err = prosody.reload_config();
452         return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
453 end
454
455 def_env.hosts = {};
456 function def_env.hosts:list()
457         for host, host_session in pairs(hosts) do
458                 self.session.print(host);
459         end
460         return true, "Done";
461 end
462
463 function def_env.hosts:add(name)
464 end
465
466 def_env.c2s = {};
467
468 local function show_c2s(callback)
469         for hostname, host in pairs(hosts) do
470                 for username, user in pairs(host.sessions or {}) do
471                         for resource, session in pairs(user.sessions or {}) do
472                                 local jid = username.."@"..hostname.."/"..resource;
473                                 callback(jid, session);
474                         end
475                 end
476         end
477 end
478
479 function def_env.c2s:count(match_jid)
480         local count = 0;
481         show_c2s(function (jid, session)
482                 if (not match_jid) or jid:match(match_jid) then
483                         count = count + 1;
484                 end             
485         end);
486         return true, "Total: "..count.." clients";
487 end
488
489 function def_env.c2s:show(match_jid)
490         local print, count = self.session.print, 0;
491         local curr_host;
492         show_c2s(function (jid, session)
493                 if curr_host ~= session.host then
494                         curr_host = session.host;
495                         print(curr_host);
496                 end
497                 if (not match_jid) or jid:match(match_jid) then
498                         count = count + 1;
499                         local status, priority = "unavailable", tostring(session.priority or "-");
500                         if session.presence then
501                                 status = session.presence:child_with_name("show");
502                                 if status then
503                                         status = status:get_text() or "[invalid!]";
504                                 else
505                                         status = "available";
506                                 end
507                         end
508                         print("   "..jid.." - "..status.."("..priority..")");
509                 end             
510         end);
511         return true, "Total: "..count.." clients";
512 end
513
514 function def_env.c2s:show_insecure(match_jid)
515         local print, count = self.session.print, 0;
516         show_c2s(function (jid, session)
517                 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
518                         count = count + 1;
519                         print(jid);
520                 end             
521         end);
522         return true, "Total: "..count.." insecure client connections";
523 end
524
525 function def_env.c2s:show_secure(match_jid)
526         local print, count = self.session.print, 0;
527         show_c2s(function (jid, session)
528                 if ((not match_jid) or jid:match(match_jid)) and session.secure then
529                         count = count + 1;
530                         print(jid);
531                 end             
532         end);
533         return true, "Total: "..count.." secure client connections";
534 end
535
536 function def_env.c2s:close(match_jid)
537         local count = 0;
538         show_c2s(function (jid, session)
539                 if jid == match_jid or jid_bare(jid) == match_jid then
540                         count = count + 1;
541                         session:close();
542                 end
543         end);
544         return true, "Total: "..count.." sessions closed";
545 end
546
547 local function session_flags(session, line)
548         if session.cert_identity_status == "valid" then
549                 line[#line+1] = "(secure)";
550         elseif session.secure then
551                 line[#line+1] = "(encrypted)";
552         end
553         if session.compressed then
554                 line[#line+1] = "(compressed)";
555         end
556         if session.smacks then
557                 line[#line+1] = "(sm)";
558         end
559         if session.conn and session.conn:ip():match(":") then
560                 line[#line+1] = "(IPv6)";
561         end
562         return table.concat(line, " ");
563 end
564
565 def_env.s2s = {};
566 function def_env.s2s:show(match_jid)
567         local _print = self.session.print;
568         local print = self.session.print;
569         
570         local count_in, count_out = 0,0;
571         
572         for host, host_session in pairs(hosts) do
573                 print = function (...) _print(host); _print(...); print = _print; end
574                 for remotehost, session in pairs(host_session.s2sout) do
575                         if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
576                                 count_out = count_out + 1;
577                                 print(session_flags(session, {"   ", host, "->", remotehost}));
578                                 if session.sendq then
579                                         print("        There are "..#session.sendq.." queued outgoing stanzas for this connection");
580                                 end
581                                 if session.type == "s2sout_unauthed" then
582                                         if session.connecting then
583                                                 print("        Connection not yet established");
584                                                 if not session.srv_hosts then
585                                                         if not session.conn then
586                                                                 print("        We do not yet have a DNS answer for this host's SRV records");
587                                                         else
588                                                                 print("        This host has no SRV records, using A record instead");
589                                                         end
590                                                 elseif session.srv_choice then
591                                                         print("        We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
592                                                         local srv_choice = session.srv_hosts[session.srv_choice];
593                                                         print("        Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
594                                                 end
595                                         elseif session.notopen then
596                                                 print("        The <stream> has not yet been opened");
597                                         elseif not session.dialback_key then
598                                                 print("        Dialback has not been initiated yet");
599                                         elseif session.dialback_key then
600                                                 print("        Dialback has been requested, but no result received");
601                                         end
602                                 end
603                         end
604                 end     
605                 local subhost_filter = function (h)
606                                 return (match_jid and h:match(match_jid));
607                         end
608                 for session in pairs(incoming_s2s) do
609                         if session.to_host == host and ((not match_jid) or host:match(match_jid)
610                                 or (session.from_host and session.from_host:match(match_jid))
611                                 -- Pft! is what I say to list comprehensions
612                                 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
613                                 count_in = count_in + 1;
614                                 print(session_flags(session, {"   ", host, "<-", session.from_host or "(unknown)"}));
615                                 if session.type == "s2sin_unauthed" then
616                                                 print("        Connection not yet authenticated");
617                                 end
618                                 for name in pairs(session.hosts) do
619                                         if name ~= session.from_host then
620                                                 print("        also hosts "..tostring(name));
621                                         end
622                                 end
623                         end
624                 end
625                 
626                 print = _print;
627         end
628         
629         for session in pairs(incoming_s2s) do
630                 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
631                         count_in = count_in + 1;
632                         print("Other incoming s2s connections");
633                         print("    (unknown) <- "..(session.from_host or "(unknown)"));                 
634                 end
635         end
636         
637         return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
638 end
639
640 local function print_subject(print, subject)
641         for _, entry in ipairs(subject) do
642                 print(
643                         ("    %s: %q"):format(
644                                 entry.name or entry.oid,
645                                 entry.value:gsub("[\r\n%z%c]", " ")
646                         )
647                 );
648         end
649 end
650
651 -- As much as it pains me to use the 0-based depths that OpenSSL does,
652 -- I think there's going to be more confusion among operators if we
653 -- break from that.
654 local function print_errors(print, errors)
655         for depth, t in ipairs(errors) do
656                 print(
657                         ("    %d: %s"):format(
658                                 depth-1,
659                                 table.concat(t, "\n|        ")
660                         )
661                 );
662         end
663 end
664
665 function def_env.s2s:showcert(domain)
666         local ser = require "util.serialization".serialize;
667         local print = self.session.print;
668         local domain_sessions = set.new(array.collect(keys(incoming_s2s)))
669                 /function(session) return session.from_host == domain and session or nil; end;
670         for local_host in values(prosody.hosts) do
671                 local s2sout = local_host.s2sout;
672                 if s2sout and s2sout[domain] then
673                         domain_sessions:add(s2sout[domain]);
674                 end
675         end
676         local cert_set = {};
677         for session in domain_sessions do
678                 local conn = session.conn;
679                 conn = conn and conn:socket();
680                 if not conn.getpeerchain then
681                         if conn.dohandshake then
682                                 error("This version of LuaSec does not support certificate viewing");
683                         end
684                 else
685                         local cert = conn:getpeercertificate();
686                         if cert then
687                                 local certs = conn:getpeerchain();
688                                 local digest = cert:digest("sha1");
689                                 if not cert_set[digest] then
690                                         local chain_valid, chain_errors = conn:getpeerverification();
691                                         cert_set[digest] = {
692                                                 {
693                                                   from = session.from_host,
694                                                   to = session.to_host,
695                                                   direction = session.direction
696                                                 };
697                                                 chain_valid = chain_valid;
698                                                 chain_errors = chain_errors;
699                                                 certs = certs;
700                                         };
701                                 else
702                                         table.insert(cert_set[digest], {
703                                                 from = session.from_host,
704                                                 to = session.to_host,
705                                                 direction = session.direction
706                                         });
707                                 end
708                         end
709                 end
710         end
711         local domain_certs = array.collect(values(cert_set));
712         -- Phew. We now have a array of unique certificates presented by domain.
713         local n_certs = #domain_certs;
714         
715         if n_certs == 0 then
716                 return "No certificates found for "..domain;
717         end
718         
719         local function _capitalize_and_colon(byte)
720                 return string.upper(byte)..":";
721         end
722         local function pretty_fingerprint(hash)
723                 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
724         end
725         
726         for cert_info in values(domain_certs) do
727                 local certs = cert_info.certs;
728                 local cert = certs[1];
729                 print("---")
730                 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
731                 print("");
732                 local n_streams = #cert_info;
733                 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
734                 for _, stream in ipairs(cert_info) do
735                         if stream.direction == "incoming" then
736                                 print("    "..stream.to.." <- "..stream.from);
737                         else
738                                 print("    "..stream.from.." -> "..stream.to);
739                         end
740                 end
741                 print("");
742                 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
743                 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
744                 if chain_valid then
745                         print("Trusted certificate: Yes");
746                 else
747                         print("Trusted certificate: No");
748                         print_errors(print, errors);
749                 end
750                 print("");
751                 print("Issuer: ");
752                 print_subject(print, cert:issuer());
753                 print("");
754                 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
755                 print("Subject:");
756                 print_subject(print, cert:subject());
757         end
758         print("---");
759         return ("Showing "..n_certs.." certificate"
760                 ..(n_certs==1 and "" or "s")
761                 .." presented by "..domain..".");
762 end
763
764 function def_env.s2s:close(from, to)
765         local print, count = self.session.print, 0;
766         
767         if not (from and to) then
768                 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
769         elseif from == to then
770                 return false, "Both from and to are the same... you can't do that :)";
771         end
772         
773         if hosts[from] and not hosts[to] then
774                 -- Is an outgoing connection
775                 local session = hosts[from].s2sout[to];
776                 if not session then
777                         print("No outgoing connection from "..from.." to "..to)
778                 else
779                         (session.close or s2smanager.destroy_session)(session);
780                         count = count + 1;
781                         print("Closed outgoing session from "..from.." to "..to);
782                 end
783         elseif hosts[to] and not hosts[from] then
784                 -- Is an incoming connection
785                 for session in pairs(incoming_s2s) do
786                         if session.to_host == to and session.from_host == from then
787                                 (session.close or s2smanager.destroy_session)(session);
788                                 count = count + 1;
789                         end
790                 end
791                 
792                 if count == 0 then
793                         print("No incoming connections from "..from.." to "..to);
794                 else
795                         print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
796                 end
797         elseif hosts[to] and hosts[from] then
798                 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
799         else
800                 return false, "Neither of the hostnames you specified are being used on this server";
801         end
802         
803         return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
804 end
805
806 function def_env.s2s:closeall(host)
807         local count = 0;
808
809         if not host or type(host) ~= "string" then return false, "wrong syntax: please use s2s:closeall('hostname.tld')"; end
810         if hosts[host] then
811                 for session in pairs(incoming_s2s) do
812                         if session.to_host == host then
813                                 (session.close or s2smanager.destroy_session)(session);
814                                 count = count + 1;
815                         end
816                 end
817                 for _, session in pairs(hosts[host].s2sout) do
818                         (session.close or s2smanager.destroy_session)(session);
819                         count = count + 1;
820                 end
821         else
822                 for session in pairs(incoming_s2s) do
823                         if session.from_host == host then
824                                 (session.close or s2smanager.destroy_session)(session);
825                                 count = count + 1;
826                         end
827                 end
828                 for _, h in pairs(hosts) do
829                         if h.s2sout[host] then
830                                 (h.s2sout[host].close or s2smanager.destroy_session)(h.s2sout[host]);
831                                 count = count + 1;
832                         end
833                 end
834         end
835
836         if count == 0 then return false, "No sessions to close.";
837         else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
838 end
839
840 def_env.host = {}; def_env.hosts = def_env.host;
841
842 function def_env.host:activate(hostname, config)
843         return hostmanager.activate(hostname, config);
844 end
845 function def_env.host:deactivate(hostname, reason)
846         return hostmanager.deactivate(hostname, reason);
847 end
848
849 function def_env.host:list()
850         local print = self.session.print;
851         local i = 0;
852         for host in values(array.collect(keys(prosody.hosts)):sort()) do
853                 i = i + 1;
854                 print(host);
855         end
856         return true, i.." hosts";
857 end
858
859 def_env.port = {};
860
861 function def_env.port:list()
862         local print = self.session.print;
863         local services = portmanager.get_active_services().data;
864         local ordered_services, n_ports = {}, 0;
865         for service, interfaces in pairs(services) do
866                 table.insert(ordered_services, service);
867         end
868         table.sort(ordered_services);
869         for _, service in ipairs(ordered_services) do
870                 local ports_list = {};
871                 for interface, ports in pairs(services[service]) do
872                         for port in pairs(ports) do
873                                 table.insert(ports_list, "["..interface.."]:"..port);
874                         end
875                 end
876                 n_ports = n_ports + #ports_list;
877                 print(service..": "..table.concat(ports_list, ", "));
878         end
879         return true, #ordered_services.." services listening on "..n_ports.." ports";
880 end
881
882 function def_env.port:close(close_port, close_interface)
883         close_port = assert(tonumber(close_port), "Invalid port number");
884         local n_closed = 0;
885         local services = portmanager.get_active_services().data;
886         for service, interfaces in pairs(services) do
887                 for interface, ports in pairs(interfaces) do
888                         if not close_interface or close_interface == interface then
889                                 if ports[close_port] then
890                                         self.session.print("Closing ["..interface.."]:"..close_port.."...");
891                                         local ok, err = portmanager.close(interface, close_port)
892                                         if not ok then
893                                                 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
894                                         else
895                                                 n_closed = n_closed + 1;
896                                         end
897                                 end
898                         end
899                 end
900         end
901         return true, "Closed "..n_closed.." ports";
902 end
903
904 def_env.muc = {};
905
906 local console_room_mt = {
907         __index = function (self, k) return self.room[k]; end;
908         __tostring = function (self)
909                 return "MUC room <"..self.room.jid..">";
910         end;
911 };
912
913 local function check_muc(jid)
914         local room_name, host = jid_split(jid);
915         if not hosts[host] then
916                 return nil, "No such host: "..host;
917         elseif not hosts[host].modules.muc then
918                 return nil, "Host '"..host.."' is not a MUC service";
919         end
920         return room_name, host;
921 end
922
923 function def_env.muc:create(room_jid)
924         local room, host = check_muc(room_jid);
925         return hosts[host].modules.muc.create_room(room_jid);
926 end
927
928 function def_env.muc:room(room_jid)
929         local room_name, host = check_muc(room_jid);
930         local room_obj = hosts[host].modules.muc.rooms[room_jid];
931         if not room_obj then
932                 return nil, "No such room: "..room_jid;
933         end
934         return setmetatable({ room = room_obj }, console_room_mt);
935 end
936
937 local um = require"core.usermanager";
938
939 def_env.user = {};
940 function def_env.user:create(jid, password)
941         local username, host = jid_split(jid);
942         if um.user_exists(username, host) then
943                 return nil, "User exists";
944         end
945         local ok, err = um.create_user(username, password, host);
946         if ok then
947                 return true, "User created";
948         else
949                 return nil, "Could not create user: "..err;
950         end
951 end
952
953 function def_env.user:delete(jid)
954         local username, host = jid_split(jid);
955         if not um.user_exists(username, host) then
956                 return nil, "No such user";
957         end
958         local ok, err = um.delete_user(username, host);
959         if ok then
960                 return true, "User deleted";
961         else
962                 return nil, "Could not delete user: "..err;
963         end
964 end
965
966 function def_env.user:password(jid, password)
967         local username, host = jid_split(jid);
968         if not um.user_exists(username, host) then
969                 return nil, "No such user";
970         end
971         local ok, err = um.set_password(username, password, host);
972         if ok then
973                 return true, "User password changed";
974         else
975                 return nil, "Could not change password for user: "..err;
976         end
977 end
978
979 function def_env.user:list(host, pat)
980         if not host then
981                 return nil, "No host given";
982         elseif not hosts[host] then
983                 return nil, "No such host";
984         end
985         local print = self.session.print;
986         local total, matches = 0, 0;
987         for user in um.users(host) do
988                 if not pat or user:match(pat) then
989                         print(user.."@"..host);
990                         matches = matches + 1;
991                 end
992                 total = total + 1;
993         end
994         return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
995 end
996
997 def_env.xmpp = {};
998
999 local st = require "util.stanza";
1000 function def_env.xmpp:ping(localhost, remotehost)
1001         if hosts[localhost] then
1002                 core_post_stanza(hosts[localhost],
1003                         st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
1004                                 :tag("ping", {xmlns="urn:xmpp:ping"}));
1005                 return true, "Sent ping";
1006         else
1007                 return nil, "No such host";
1008         end
1009 end
1010
1011 def_env.dns = {};
1012 local adns = require"net.adns";
1013 local dns = require"net.dns";
1014
1015 function def_env.dns:lookup(name, typ, class)
1016         local ret = "Query sent";
1017         local print = self.session.print;
1018         local function handler(...)
1019                 ret = "Got response";
1020                 print(...);
1021         end
1022         adns.lookup(handler, name, typ, class);
1023         return true, ret;
1024 end
1025
1026 function def_env.dns:addnameserver(...)
1027         dns.addnameserver(...)
1028         return true
1029 end
1030
1031 function def_env.dns:setnameserver(...)
1032         dns.setnameserver(...)
1033         return true
1034 end
1035
1036 function def_env.dns:purge()
1037         dns.purge()
1038         return true
1039 end
1040
1041 function def_env.dns:cache()
1042         return true, "Cache:\n"..tostring(dns.cache())
1043 end
1044
1045 -------------
1046
1047 function printbanner(session)
1048         local option = module:get_option("console_banner");
1049         if option == nil or option == "full" or option == "graphic" then
1050                 session.print [[
1051                    ____                \   /     _       
1052                     |  _ \ _ __ ___  ___  _-_   __| |_   _ 
1053                     | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1054                     |  __/| | | (_) \__ \ |_| | (_| | |_| |
1055                     |_|   |_|  \___/|___/\___/ \__,_|\__, |
1056                     A study in simplicity            |___/ 
1057
1058 ]]
1059         end
1060         if option == nil or option == "short" or option == "full" then
1061         session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1062         session.print("You may find more help on using this console in our online documentation at ");
1063         session.print("http://prosody.im/doc/console\n");
1064         end
1065         if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
1066                 if type(option) == "string" then
1067                         session.print(option)
1068                 elseif type(option) == "function" then
1069                         module:log("warn", "Using functions as value for the console_banner option is no longer supported");
1070                 end
1071         end
1072 end
1073
1074 module:provides("net", {
1075         name = "console";
1076         listener = console_listener;
1077         default_port = 5582;
1078         private = true;
1079 });