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