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