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