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