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