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