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