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