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 = require "util.jid";
26 local jid_bare, jid_split = jid.bare, jid.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 local function session_flags(session, line)
487         line = line or {};
488         if session.cert_identity_status == "valid" then
489                 line[#line+1] = "(secure)";
490         elseif session.secure then
491                 line[#line+1] = "(encrypted)";
492         end
493         if session.compressed then
494                 line[#line+1] = "(compressed)";
495         end
496         if session.smacks then
497                 line[#line+1] = "(sm)";
498         end
499         if session.ip and session.ip:match(":") then
500                 line[#line+1] = "(IPv6)";
501         end
502         return table.concat(line, " ");
503 end
504
505 def_env.c2s = {};
506
507 local function show_c2s(callback)
508         for hostname, host in pairs(hosts) do
509                 for username, user in pairs(host.sessions or {}) do
510                         for resource, session in pairs(user.sessions or {}) do
511                                 local jid = username.."@"..hostname.."/"..resource;
512                                 callback(jid, session);
513                         end
514                 end
515         end
516 end
517
518 function def_env.c2s:count(match_jid)
519         local count = 0;
520         show_c2s(function (jid, session)
521                 if (not match_jid) or jid:match(match_jid) then
522                         count = count + 1;
523                 end
524         end);
525         return true, "Total: "..count.." clients";
526 end
527
528 function def_env.c2s:show(match_jid)
529         local print, count = self.session.print, 0;
530         local curr_host;
531         show_c2s(function (jid, session)
532                 if curr_host ~= session.host then
533                         curr_host = session.host;
534                         print(curr_host);
535                 end
536                 if (not match_jid) or jid:match(match_jid) then
537                         count = count + 1;
538                         local status, priority = "unavailable", tostring(session.priority or "-");
539                         if session.presence then
540                                 status = session.presence:get_child_text("show") or "available";
541                         end
542                         print(session_flags(session, { "   "..jid.." - "..status.."("..priority..")" }));
543                 end
544         end);
545         return true, "Total: "..count.." clients";
546 end
547
548 function def_env.c2s:show_insecure(match_jid)
549         local print, count = self.session.print, 0;
550         show_c2s(function (jid, session)
551                 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
552                         count = count + 1;
553                         print(jid);
554                 end
555         end);
556         return true, "Total: "..count.." insecure client connections";
557 end
558
559 function def_env.c2s:show_secure(match_jid)
560         local print, count = self.session.print, 0;
561         show_c2s(function (jid, session)
562                 if ((not match_jid) or jid:match(match_jid)) and session.secure then
563                         count = count + 1;
564                         print(jid);
565                 end
566         end);
567         return true, "Total: "..count.." secure client connections";
568 end
569
570 function def_env.c2s:close(match_jid)
571         local count = 0;
572         show_c2s(function (jid, session)
573                 if jid == match_jid or jid_bare(jid) == match_jid then
574                         count = count + 1;
575                         session:close();
576                 end
577         end);
578         return true, "Total: "..count.." sessions closed";
579 end
580
581
582 def_env.s2s = {};
583 function def_env.s2s:show(match_jid)
584         local print = self.session.print;
585
586         local count_in, count_out = 0,0;
587         local s2s_list = { };
588
589         local s2s_sessions = module:shared"/*/s2s/sessions";
590         for _, session in pairs(s2s_sessions) do
591                 local remotehost, localhost, direction;
592                 if session.direction == "outgoing" then
593                         direction = "->";
594                         count_out = count_out + 1;
595                         remotehost, localhost = session.to_host or "?", session.from_host or "?";
596                 else
597                         direction = "<-";
598                         count_in = count_in + 1;
599                         remotehost, localhost = session.from_host or "?", session.to_host or "?";
600                 end
601                 local sess_lines = { l = localhost, r = remotehost,
602                         session_flags(session, { "", direction, remotehost or "?",
603                                 "["..session.type..tostring(session):match("[a-f0-9]*$").."]" })};
604
605                 if (not match_jid) or remotehost:match(match_jid) or localhost:match(match_jid) then
606                         table.insert(s2s_list, sess_lines);
607                         local print = function (s) table.insert(sess_lines, "        "..s); end
608                         if session.sendq then
609                                 print("There are "..#session.sendq.." queued outgoing stanzas for this connection");
610                         end
611                         if session.type == "s2sout_unauthed" then
612                                 if session.connecting then
613                                         print("Connection not yet established");
614                                         if not session.srv_hosts then
615                                                 if not session.conn then
616                                                         print("We do not yet have a DNS answer for this host's SRV records");
617                                                 else
618                                                         print("This host has no SRV records, using A record instead");
619                                                 end
620                                         elseif session.srv_choice then
621                                                 print("We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
622                                                 local srv_choice = session.srv_hosts[session.srv_choice];
623                                                 print("Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
624                                         end
625                                 elseif session.notopen then
626                                         print("The <stream> has not yet been opened");
627                                 elseif not session.dialback_key then
628                                         print("Dialback has not been initiated yet");
629                                 elseif session.dialback_key then
630                                         print("Dialback has been requested, but no result received");
631                                 end
632                         end
633                         if session.type == "s2sin_unauthed" then
634                                 print("Connection not yet authenticated");
635                         elseif session.type == "s2sin" then
636                                 for name in pairs(session.hosts) do
637                                         if name ~= session.from_host then
638                                                 print("also hosts "..tostring(name));
639                                         end
640                                 end
641                         end
642                 end
643         end
644
645         -- Sort by local host, then remote host
646         table.sort(s2s_list, function(a,b)
647                 if a.l == b.l then return a.r < b.r; end
648                 return a.l < b.l;
649         end);
650         local lasthost;
651         for _, sess_lines in ipairs(s2s_list) do
652                 if sess_lines.l ~= lasthost then print(sess_lines.l); lasthost=sess_lines.l end
653                 for _, line in ipairs(sess_lines) do print(line); end
654         end
655         return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
656 end
657
658 local function print_subject(print, subject)
659         for _, entry in ipairs(subject) do
660                 print(
661                         ("    %s: %q"):format(
662                                 entry.name or entry.oid,
663                                 entry.value:gsub("[\r\n%z%c]", " ")
664                         )
665                 );
666         end
667 end
668
669 -- As much as it pains me to use the 0-based depths that OpenSSL does,
670 -- I think there's going to be more confusion among operators if we
671 -- break from that.
672 local function print_errors(print, errors)
673         for depth, t in pairs(errors) do
674                 print(
675                         ("    %d: %s"):format(
676                                 depth-1,
677                                 table.concat(t, "\n|        ")
678                         )
679                 );
680         end
681 end
682
683 function def_env.s2s:showcert(domain)
684         local ser = require "util.serialization".serialize;
685         local print = self.session.print;
686         local s2s_sessions = module:shared"/*/s2s/sessions";
687         local domain_sessions = set.new(array.collect(values(s2s_sessions)))
688                 /function(session) return (session.to_host == domain or session.from_host == domain) and session or nil; end;
689         local cert_set = {};
690         for session in domain_sessions do
691                 local conn = session.conn;
692                 conn = conn and conn:socket();
693                 if not conn.getpeerchain then
694                         if conn.dohandshake then
695                                 error("This version of LuaSec does not support certificate viewing");
696                         end
697                 else
698                         local cert = conn:getpeercertificate();
699                         if cert then
700                                 local certs = conn:getpeerchain();
701                                 local digest = cert:digest("sha1");
702                                 if not cert_set[digest] then
703                                         local chain_valid, chain_errors = conn:getpeerverification();
704                                         cert_set[digest] = {
705                                                 {
706                                                   from = session.from_host,
707                                                   to = session.to_host,
708                                                   direction = session.direction
709                                                 };
710                                                 chain_valid = chain_valid;
711                                                 chain_errors = chain_errors;
712                                                 certs = certs;
713                                         };
714                                 else
715                                         table.insert(cert_set[digest], {
716                                                 from = session.from_host,
717                                                 to = session.to_host,
718                                                 direction = session.direction
719                                         });
720                                 end
721                         end
722                 end
723         end
724         local domain_certs = array.collect(values(cert_set));
725         -- Phew. We now have a array of unique certificates presented by domain.
726         local n_certs = #domain_certs;
727
728         if n_certs == 0 then
729                 return "No certificates found for "..domain;
730         end
731
732         local function _capitalize_and_colon(byte)
733                 return string.upper(byte)..":";
734         end
735         local function pretty_fingerprint(hash)
736                 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
737         end
738
739         for cert_info in values(domain_certs) do
740                 local certs = cert_info.certs;
741                 local cert = certs[1];
742                 print("---")
743                 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
744                 print("");
745                 local n_streams = #cert_info;
746                 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
747                 for _, stream in ipairs(cert_info) do
748                         if stream.direction == "incoming" then
749                                 print("    "..stream.to.." <- "..stream.from);
750                         else
751                                 print("    "..stream.from.." -> "..stream.to);
752                         end
753                 end
754                 print("");
755                 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
756                 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
757                 if chain_valid then
758                         print("Trusted certificate: Yes");
759                 else
760                         print("Trusted certificate: No");
761                         print_errors(print, errors);
762                 end
763                 print("");
764                 print("Issuer: ");
765                 print_subject(print, cert:issuer());
766                 print("");
767                 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
768                 print("Subject:");
769                 print_subject(print, cert:subject());
770         end
771         print("---");
772         return ("Showing "..n_certs.." certificate"
773                 ..(n_certs==1 and "" or "s")
774                 .." presented by "..domain..".");
775 end
776
777 function def_env.s2s:close(from, to)
778         local print, count = self.session.print, 0;
779         local s2s_sessions = module:shared"/*/s2s/sessions";
780
781         local match_id;
782         if from and not to then
783                 match_id, from = from;
784         elseif not to then
785                 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
786         elseif from == to then
787                 return false, "Both from and to are the same... you can't do that :)";
788         end
789
790         for _, session in pairs(s2s_sessions) do
791                 local id = session.type..tostring(session):match("[a-f0-9]+$");
792                 if (match_id and match_id == id)
793                 or (session.from_host == from and session.to_host == to) then
794                         print(("Closing connection from %s to %s [%s]"):format(session.from_host, session.to_host, id));
795                         (session.close or s2smanager.destroy_session)(session);
796                         count = count + 1 ;
797                 end
798                         end
799         return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
800 end
801
802 function def_env.s2s:closeall(host)
803         local count = 0;
804         local s2s_sessions = module:shared"/*/s2s/sessions";
805         for _,session in pairs(s2s_sessions) do
806                 if not host or session.from_host == host or session.to_host == host then
807                         session:close();
808                                 count = count + 1;
809                         end
810                 end
811         if count == 0 then return false, "No sessions to close.";
812         else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
813 end
814
815 def_env.host = {}; def_env.hosts = def_env.host;
816
817 function def_env.host:activate(hostname, config)
818         return hostmanager.activate(hostname, config);
819 end
820 function def_env.host:deactivate(hostname, reason)
821         return hostmanager.deactivate(hostname, reason);
822 end
823
824 function def_env.host:list()
825         local print = self.session.print;
826         local i = 0;
827         for host in values(array.collect(keys(prosody.hosts)):sort()) do
828                 i = i + 1;
829                 print(host);
830         end
831         return true, i.." hosts";
832 end
833
834 def_env.port = {};
835
836 function def_env.port:list()
837         local print = self.session.print;
838         local services = portmanager.get_active_services().data;
839         local ordered_services, n_ports = {}, 0;
840         for service, interfaces in pairs(services) do
841                 table.insert(ordered_services, service);
842         end
843         table.sort(ordered_services);
844         for _, service in ipairs(ordered_services) do
845                 local ports_list = {};
846                 for interface, ports in pairs(services[service]) do
847                         for port in pairs(ports) do
848                                 table.insert(ports_list, "["..interface.."]:"..port);
849                         end
850                 end
851                 n_ports = n_ports + #ports_list;
852                 print(service..": "..table.concat(ports_list, ", "));
853         end
854         return true, #ordered_services.." services listening on "..n_ports.." ports";
855 end
856
857 function def_env.port:close(close_port, close_interface)
858         close_port = assert(tonumber(close_port), "Invalid port number");
859         local n_closed = 0;
860         local services = portmanager.get_active_services().data;
861         for service, interfaces in pairs(services) do
862                 for interface, ports in pairs(interfaces) do
863                         if not close_interface or close_interface == interface then
864                                 if ports[close_port] then
865                                         self.session.print("Closing ["..interface.."]:"..close_port.."...");
866                                         local ok, err = portmanager.close(interface, close_port)
867                                         if not ok then
868                                                 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
869                                         else
870                                                 n_closed = n_closed + 1;
871                                         end
872                                 end
873                         end
874                 end
875         end
876         return true, "Closed "..n_closed.." ports";
877 end
878
879 def_env.muc = {};
880
881 local console_room_mt = {
882         __index = function (self, k) return self.room[k]; end;
883         __tostring = function (self)
884                 return "MUC room <"..self.room.jid..">";
885         end;
886 };
887
888 local function check_muc(jid)
889         local room_name, host = jid_split(jid);
890         if not hosts[host] then
891                 return nil, "No such host: "..host;
892         elseif not hosts[host].modules.muc then
893                 return nil, "Host '"..host.."' is not a MUC service";
894         end
895         return room_name, host;
896 end
897
898 function def_env.muc:create(room_jid)
899         local room, host = check_muc(room_jid);
900         if not room then return nil, host end
901         if hosts[host].modules.muc.rooms[room_jid] then return nil, "Room exists already" end
902         return hosts[host].modules.muc.create_room(room_jid);
903 end
904
905 function def_env.muc:room(room_jid)
906         local room_name, host = check_muc(room_jid);
907         local room_obj = hosts[host].modules.muc.rooms[room_jid];
908         if not room_obj then
909                 return nil, "No such room: "..room_jid;
910         end
911         return setmetatable({ room = room_obj }, console_room_mt);
912 end
913
914 local um = require"core.usermanager";
915
916 def_env.user = {};
917 function def_env.user:create(jid, password)
918         local username, host = jid_split(jid);
919         if not hosts[host] then
920                 return nil, "No such host: "..host;
921         elseif um.user_exists(username, host) then
922                 return nil, "User exists";
923         end
924         local ok, err = um.create_user(username, password, host);
925         if ok then
926                 return true, "User created";
927         else
928                 return nil, "Could not create user: "..err;
929         end
930 end
931
932 function def_env.user:delete(jid)
933         local username, host = jid_split(jid);
934         if not hosts[host] then
935                 return nil, "No such host: "..host;
936         elseif not um.user_exists(username, host) then
937                 return nil, "No such user";
938         end
939         local ok, err = um.delete_user(username, host);
940         if ok then
941                 return true, "User deleted";
942         else
943                 return nil, "Could not delete user: "..err;
944         end
945 end
946
947 function def_env.user:password(jid, password)
948         local username, host = jid_split(jid);
949         if not hosts[host] then
950                 return nil, "No such host: "..host;
951         elseif not um.user_exists(username, host) then
952                 return nil, "No such user";
953         end
954         local ok, err = um.set_password(username, password, host);
955         if ok then
956                 return true, "User password changed";
957         else
958                 return nil, "Could not change password for user: "..err;
959         end
960 end
961
962 function def_env.user:list(host, pat)
963         if not host then
964                 return nil, "No host given";
965         elseif not hosts[host] then
966                 return nil, "No such host";
967         end
968         local print = self.session.print;
969         local total, matches = 0, 0;
970         for user in um.users(host) do
971                 if not pat or user:match(pat) then
972                         print(user.."@"..host);
973                         matches = matches + 1;
974                 end
975                 total = total + 1;
976         end
977         return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
978 end
979
980 def_env.xmpp = {};
981
982 local st = require "util.stanza";
983 function def_env.xmpp:ping(localhost, remotehost)
984         if hosts[localhost] then
985                 core_post_stanza(hosts[localhost],
986                         st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
987                                 :tag("ping", {xmlns="urn:xmpp:ping"}));
988                 return true, "Sent ping";
989         else
990                 return nil, "No such host";
991         end
992 end
993
994 def_env.dns = {};
995 local adns = require"net.adns";
996 local dns = require"net.dns";
997
998 function def_env.dns:lookup(name, typ, class)
999         local ret = "Query sent";
1000         local print = self.session.print;
1001         local function handler(...)
1002                 ret = "Got response";
1003                 print(...);
1004         end
1005         adns.lookup(handler, name, typ, class);
1006         return true, ret;
1007 end
1008
1009 function def_env.dns:addnameserver(...)
1010         dns.addnameserver(...)
1011         return true
1012 end
1013
1014 function def_env.dns:setnameserver(...)
1015         dns.setnameserver(...)
1016         return true
1017 end
1018
1019 function def_env.dns:purge()
1020         dns.purge()
1021         return true
1022 end
1023
1024 function def_env.dns:cache()
1025         return true, "Cache:\n"..tostring(dns.cache())
1026 end
1027
1028 -------------
1029
1030 function printbanner(session)
1031         local option = module:get_option("console_banner");
1032         if option == nil or option == "full" or option == "graphic" then
1033                 session.print [[
1034                    ____                \   /     _
1035                     |  _ \ _ __ ___  ___  _-_   __| |_   _
1036                     | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1037                     |  __/| | | (_) \__ \ |_| | (_| | |_| |
1038                     |_|   |_|  \___/|___/\___/ \__,_|\__, |
1039                     A study in simplicity            |___/
1040
1041 ]]
1042         end
1043         if option == nil or option == "short" or option == "full" then
1044         session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1045         session.print("You may find more help on using this console in our online documentation at ");
1046         session.print("http://prosody.im/doc/console\n");
1047         end
1048         if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
1049                 if type(option) == "string" then
1050                         session.print(option)
1051                 elseif type(option) == "function" then
1052                         module:log("warn", "Using functions as value for the console_banner option is no longer supported");
1053                 end
1054         end
1055 end
1056
1057 module:provides("net", {
1058         name = "console";
1059         listener = console_listener;
1060         default_port = 5582;
1061         private = true;
1062 });