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