mod_httpserver: Rename to mod_http_files
[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:show(match_jid)
444         local print, count = self.session.print, 0;
445         local curr_host;
446         show_c2s(function (jid, session)
447                 if curr_host ~= session.host then
448                         curr_host = session.host;
449                         print(curr_host);
450                 end
451                 if (not match_jid) or jid:match(match_jid) then
452                         count = count + 1;
453                         local status, priority = "unavailable", tostring(session.priority or "-");
454                         if session.presence then
455                                 status = session.presence:child_with_name("show");
456                                 if status then
457                                         status = status:get_text() or "[invalid!]";
458                                 else
459                                         status = "available";
460                                 end
461                         end
462                         print("   "..jid.." - "..status.."("..priority..")");
463                 end             
464         end);
465         return true, "Total: "..count.." clients";
466 end
467
468 function def_env.c2s:show_insecure(match_jid)
469         local print, count = self.session.print, 0;
470         show_c2s(function (jid, session)
471                 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
472                         count = count + 1;
473                         print(jid);
474                 end             
475         end);
476         return true, "Total: "..count.." insecure client connections";
477 end
478
479 function def_env.c2s:show_secure(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 session.secure then
483                         count = count + 1;
484                         print(jid);
485                 end             
486         end);
487         return true, "Total: "..count.." secure client connections";
488 end
489
490 function def_env.c2s:close(match_jid)
491         local print, count = self.session.print, 0;
492         show_c2s(function (jid, session)
493                 if jid == match_jid or jid_bare(jid) == match_jid then
494                         count = count + 1;
495                         session:close();
496                 end
497         end);
498         return true, "Total: "..count.." sessions closed";
499 end
500
501 def_env.s2s = {};
502 function def_env.s2s:show(match_jid)
503         local _print = self.session.print;
504         local print = self.session.print;
505         
506         local count_in, count_out = 0,0;
507         
508         for host, host_session in pairs(hosts) do
509                 print = function (...) _print(host); _print(...); print = _print; end
510                 for remotehost, session in pairs(host_session.s2sout) do
511                         if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
512                                 count_out = count_out + 1;
513                                 print("    "..host.." -> "..remotehost..(session.cert_identity_status == "valid" and " (secure)" or "")..(session.secure and " (encrypted)" or "")..(session.compressed and " (compressed)" or ""));
514                                 if session.sendq then
515                                         print("        There are "..#session.sendq.." queued outgoing stanzas for this connection");
516                                 end
517                                 if session.type == "s2sout_unauthed" then
518                                         if session.connecting then
519                                                 print("        Connection not yet established");
520                                                 if not session.srv_hosts then
521                                                         if not session.conn then
522                                                                 print("        We do not yet have a DNS answer for this host's SRV records");
523                                                         else
524                                                                 print("        This host has no SRV records, using A record instead");
525                                                         end
526                                                 elseif session.srv_choice then
527                                                         print("        We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
528                                                         local srv_choice = session.srv_hosts[session.srv_choice];
529                                                         print("        Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
530                                                 end
531                                         elseif session.notopen then
532                                                 print("        The <stream> has not yet been opened");
533                                         elseif not session.dialback_key then
534                                                 print("        Dialback has not been initiated yet");
535                                         elseif session.dialback_key then
536                                                 print("        Dialback has been requested, but no result received");
537                                         end
538                                 end
539                         end
540                 end     
541                 local subhost_filter = function (h)
542                                 return (match_jid and h:match(match_jid));
543                         end
544                 for session in pairs(incoming_s2s) do
545                         if session.to_host == host and ((not match_jid) or host:match(match_jid)
546                                 or (session.from_host and session.from_host:match(match_jid))
547                                 -- Pft! is what I say to list comprehensions
548                                 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
549                                 count_in = count_in + 1;
550                                 print("    "..host.." <- "..(session.from_host or "(unknown)")..(session.cert_identity_status == "valid" and " (secure)" or "")..(session.secure and " (encrypted)" or "")..(session.compressed and " (compressed)" or ""));
551                                 if session.type == "s2sin_unauthed" then
552                                                 print("        Connection not yet authenticated");
553                                 end
554                                 for name in pairs(session.hosts) do
555                                         if name ~= session.from_host then
556                                                 print("        also hosts "..tostring(name));
557                                         end
558                                 end
559                         end
560                 end
561                 
562                 print = _print;
563         end
564         
565         for session in pairs(incoming_s2s) do
566                 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
567                         count_in = count_in + 1;
568                         print("Other incoming s2s connections");
569                         print("    (unknown) <- "..(session.from_host or "(unknown)"));                 
570                 end
571         end
572         
573         return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
574 end
575
576 local function print_subject(print, subject)
577         for _, entry in ipairs(subject) do
578                 print(
579                         ("    %s: %q"):format(
580                                 entry.name or entry.oid,
581                                 entry.value:gsub("[\r\n%z%c]", " ")
582                         )
583                 );
584         end
585 end
586
587 -- As much as it pains me to use the 0-based depths that OpenSSL does,
588 -- I think there's going to be more confusion among operators if we
589 -- break from that.
590 local function print_errors(print, errors)
591         for depth, t in ipairs(errors) do
592                 print(
593                         ("    %d: %s"):format(
594                                 depth-1,
595                                 table.concat(t, "\n|        ")
596                         )
597                 );
598         end
599 end
600
601 function def_env.s2s:showcert(domain)
602         local ser = require "util.serialization".serialize;
603         local print = self.session.print;
604         local domain_sessions = set.new(array.collect(keys(incoming_s2s)))
605                 /function(session) return session.from_host == domain; end;
606         for local_host in values(prosody.hosts) do
607                 local s2sout = local_host.s2sout;
608                 if s2sout and s2sout[domain] then
609                         domain_sessions:add(s2sout[domain]);
610                 end
611         end
612         local cert_set = {};
613         for session in domain_sessions do
614                 local conn = session.conn;
615                 conn = conn and conn:socket();
616                 if not conn.getpeerchain then
617                         if conn.dohandshake then
618                                 error("This version of LuaSec does not support certificate viewing");
619                         end
620                 else
621                         local certs = conn:getpeerchain();
622                         local cert = certs[1];
623                         if cert then
624                                 local digest = cert:digest("sha1");
625                                 if not cert_set[digest] then
626                                         local chain_valid, chain_errors = conn:getpeerverification();
627                                         cert_set[digest] = {
628                                                 {
629                                                   from = session.from_host,
630                                                   to = session.to_host,
631                                                   direction = session.direction
632                                                 };
633                                                 chain_valid = chain_valid;
634                                                 chain_errors = chain_errors;
635                                                 certs = certs;
636                                         };
637                                 else
638                                         table.insert(cert_set[digest], {
639                                                 from = session.from_host,
640                                                 to = session.to_host,
641                                                 direction = session.direction
642                                         });
643                                 end
644                         end
645                 end
646         end
647         local domain_certs = array.collect(values(cert_set));
648         -- Phew. We now have a array of unique certificates presented by domain.
649         local print = self.session.print;
650         local n_certs = #domain_certs;
651         
652         if n_certs == 0 then
653                 return "No certificates found for "..domain;
654         end
655         
656         local function _capitalize_and_colon(byte)
657                 return string.upper(byte)..":";
658         end
659         local function pretty_fingerprint(hash)
660                 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
661         end
662         
663         for cert_info in values(domain_certs) do
664                 local certs = cert_info.certs;
665                 local cert = certs[1];
666                 print("---")
667                 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
668                 print("");
669                 local n_streams = #cert_info;
670                 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
671                 for _, stream in ipairs(cert_info) do
672                         if stream.direction == "incoming" then
673                                 print("    "..stream.to.." <- "..stream.from);
674                         else
675                                 print("    "..stream.from.." -> "..stream.to);
676                         end
677                 end
678                 print("");
679                 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
680                 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
681                 if chain_valid then
682                         print("Trusted certificate: Yes");
683                 else
684                         print("Trusted certificate: No");
685                         print_errors(print, errors);
686                 end
687                 print("");
688                 print("Issuer: ");
689                 print_subject(print, cert:issuer());
690                 print("");
691                 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
692                 print("Subject:");
693                 print_subject(print, cert:subject());
694         end
695         print("---");
696         return ("Showing "..n_certs.." certificate"
697                 ..(n_certs==1 and "" or "s")
698                 .." presented by "..domain..".");
699 end
700
701 function def_env.s2s:close(from, to)
702         local print, count = self.session.print, 0;
703         
704         if not (from and to) then
705                 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
706         elseif from == to then
707                 return false, "Both from and to are the same... you can't do that :)";
708         end
709         
710         if hosts[from] and not hosts[to] then
711                 -- Is an outgoing connection
712                 local session = hosts[from].s2sout[to];
713                 if not session then
714                         print("No outgoing connection from "..from.." to "..to)
715                 else
716                         (session.close or s2smanager.destroy_session)(session);
717                         count = count + 1;
718                         print("Closed outgoing session from "..from.." to "..to);
719                 end
720         elseif hosts[to] and not hosts[from] then
721                 -- Is an incoming connection
722                 for session in pairs(incoming_s2s) do
723                         if session.to_host == to and session.from_host == from then
724                                 (session.close or s2smanager.destroy_session)(session);
725                                 count = count + 1;
726                         end
727                 end
728                 
729                 if count == 0 then
730                         print("No incoming connections from "..from.." to "..to);
731                 else
732                         print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
733                 end
734         elseif hosts[to] and hosts[from] then
735                 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
736         else
737                 return false, "Neither of the hostnames you specified are being used on this server";
738         end
739         
740         return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
741 end
742
743 def_env.host = {}; def_env.hosts = def_env.host;
744
745 function def_env.host:activate(hostname, config)
746         return hostmanager.activate(hostname, config);
747 end
748 function def_env.host:deactivate(hostname, reason)
749         return hostmanager.deactivate(hostname, reason);
750 end
751
752 function def_env.host:list()
753         local print = self.session.print;
754         local i = 0;
755         for host in values(array.collect(keys(prosody.hosts)):sort()) do
756                 i = i + 1;
757                 print(host);
758         end
759         return true, i.." hosts";
760 end
761
762 -------------
763
764 function printbanner(session)
765         local option = config.get("*", "core", "console_banner");
766 if option == nil or option == "full" or option == "graphic" then
767 session.print [[
768                    ____                \   /     _       
769                     |  _ \ _ __ ___  ___  _-_   __| |_   _ 
770                     | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
771                     |  __/| | | (_) \__ \ |_| | (_| | |_| |
772                     |_|   |_|  \___/|___/\___/ \__,_|\__, |
773                     A study in simplicity            |___/ 
774
775 ]]
776 end
777 if option == nil or option == "short" or option == "full" then
778 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
779 session.print("You may find more help on using this console in our online documentation at ");
780 session.print("http://prosody.im/doc/console\n");
781 end
782 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
783         if type(option) == "string" then
784                 session.print(option)
785         elseif type(option) == "function" then
786                 setfenv(option, redirect_output(_G, session));
787                 pcall(option, session);
788         end
789 end
790 end
791
792 require "core.portmanager".register_service("console", {
793         listener = console_listener;
794         default_port = 5582;
795         private = true;
796 });