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