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