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