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