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