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