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