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