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