2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
13 local prosody = _G.prosody;
14 local hosts = prosody.hosts;
16 local console_listener = { default_port = 5582; default_mode = "*l"; interface = "127.0.0.1" };
18 local iterators = require "util.iterators";
19 local keys, values = iterators.keys, iterators.values;
20 local jid_bare = require "util.jid".bare;
21 local set, array = require "util.set", require "util.array";
22 local cert_verify_identity = require "util.x509".verify_identity;
24 local commands = module:shared("commands")
25 local def_env = module:shared("env");
26 local default_env_mt = { __index = def_env };
28 local function redirect_output(_G, session)
29 local env = setmetatable({ print = session.print }, { __index = function (t, k) return rawget(_G, k); end });
30 env.dofile = function(name)
31 local f, err = loadfile(name);
32 if not f then return f, err; end
33 return setfenv(f, env)();
40 function console:new_session(conn)
41 local w = function(s) conn:write(s:gsub("\n", "\r\n")); end;
42 local session = { conn = conn;
43 send = function (t) w(tostring(t)); end;
44 print = function (...)
46 for i=1,select("#", ...) do
47 t[i] = tostring(select(i, ...));
49 w("| "..table.concat(t, "\t").."\n");
51 disconnect = function () conn:close(); end;
53 session.env = setmetatable({}, default_env_mt);
55 -- Load up environment with helper objects
56 for name, t in pairs(def_env) do
57 if type(t) == "table" then
58 session.env[name] = setmetatable({ session = session }, { __index = t });
67 function console_listener.onconnect(conn)
68 -- Handle new connection
69 local session = console:new_session(conn);
70 sessions[conn] = session;
72 session.send(string.char(0));
75 function console_listener.onincoming(conn, data)
76 local session = sessions[conn];
79 (function(session, data)
82 if data:match("^>") then
83 data = data:gsub("^>", "");
85 elseif data == "\004" then
86 commands["bye"](session, data);
89 local command = data:lower();
90 command = data:match("^%w+") or data:match("%p");
91 if commands[command] then
92 commands[command](session, data);
99 local chunkname = "=console";
100 local chunk, err = loadstring("return "..data, chunkname);
102 chunk, err = loadstring(data, chunkname);
104 err = err:gsub("^%[string .-%]:%d+: ", "");
105 err = err:gsub("^:%d+: ", "");
106 err = err:gsub("'<eof>'", "the end of the line");
107 session.print("Sorry, I couldn't understand that... "..err);
112 setfenv(chunk, (useglobalenv and redirect_output(_G, session)) or session.env or nil);
114 local ranok, taskok, message = pcall(chunk);
116 if not (ranok or message or useglobalenv) and commands[data:lower()] then
117 commands[data:lower()](session, data);
122 session.print("Fatal error while running command, it did not complete");
123 session.print("Error: "..taskok);
128 session.print("Result: "..tostring(taskok));
130 elseif (not taskok) and message then
131 session.print("Command completed with a problem");
132 session.print("Message: "..tostring(message));
136 session.print("OK: "..tostring(message));
139 session.send(string.char(0));
142 function console_listener.ondisconnect(conn, err)
143 local session = sessions[conn];
145 session.disconnect();
146 sessions[conn] = nil;
150 -- Console commands --
151 -- These are simple commands, not valid standalone in Lua
153 function commands.bye(session)
154 session.print("See you! :)");
155 session.disconnect();
157 commands.quit, commands.exit = commands.bye, commands.bye;
159 commands["!"] = function (session, data)
160 if data:match("^!!") and session.env._ then
161 session.print("!> "..session.env._);
162 return console_listener.onincoming(session.conn, session.env._);
164 local old, new = data:match("^!(.-[^\\])!(.-)!$");
166 local ok, res = pcall(string.gsub, session.env._, old, new);
171 session.print("!> "..res);
172 return console_listener.onincoming(session.conn, res);
174 session.print("Sorry, not sure what you want");
178 function commands.help(session, data)
179 local print = session.print;
180 local section = data:match("^help (%w+)");
182 print [[Commands are divided into multiple sections. For help on a particular section, ]]
183 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
185 print [[c2s - Commands to manage local client-to-server sessions]]
186 print [[s2s - Commands to manage sessions between this server and others]]
187 print [[module - Commands to load/reload/unload modules/plugins]]
188 print [[host - Commands to activate, deactivate and list virtual hosts]]
189 print [[server - Uptime, version, shutting down, etc.]]
190 print [[config - Reloading the configuration, etc.]]
191 print [[console - Help regarding the console itself]]
192 elseif section == "c2s" then
193 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
194 print [[c2s:show_insecure() - Show all unencrypted client connections]]
195 print [[c2s:show_secure() - Show all encrypted client connections]]
196 print [[c2s:close(jid) - Close all sessions for the specified JID]]
197 elseif section == "s2s" then
198 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
199 print [[s2s:close(from, to) - Close a connection from one domain to another]]
200 elseif section == "module" then
201 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
202 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
203 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
204 print [[module:list(host) - List the modules loaded on the specified host]]
205 elseif section == "host" then
206 print [[host:activate(hostname) - Activates the specified host]]
207 print [[host:deactivate(hostname) - Disconnects all clients on this host and deactivates]]
208 print [[host:list() - List the currently-activated hosts]]
209 elseif section == "server" then
210 print [[server:version() - Show the server's version number]]
211 print [[server:uptime() - Show how long the server has been running]]
212 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
213 elseif section == "config" then
214 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
215 elseif section == "console" then
216 print [[Hey! Welcome to Prosody's admin console.]]
217 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
218 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
219 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
221 print [[For now we offer a couple of handy shortcuts:]]
222 print [[!! - Repeat the last command]]
223 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
225 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
226 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
227 print [[the running server. Great fun, but be careful not to break anything :)]]
232 -- Session environment --
233 -- Anything in def_env will be accessible within the session as a global variable
237 function def_env.server:insane_reload()
238 prosody.unlock_globals();
240 prosody = _G.prosody;
241 return true, "Server reloaded";
244 function def_env.server:version()
245 return true, tostring(prosody.version or "unknown");
248 function def_env.server:uptime()
249 local t = os.time()-prosody.start_time;
250 local seconds = t%60;
251 t = (t - seconds)/60;
252 local minutes = t%60;
253 t = (t - minutes)/60;
257 return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
258 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
259 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
262 function def_env.server:shutdown(reason)
263 prosody.shutdown(reason);
264 return true, "Shutdown initiated";
269 local function get_hosts_set(hosts, module)
270 if type(hosts) == "table" then
272 return set.new(hosts);
273 elseif hosts._items then
276 elseif type(hosts) == "string" then
277 return set.new { hosts };
278 elseif hosts == nil then
279 local mm = require "modulemanager";
280 local hosts_set = set.new(array.collect(keys(prosody.hosts)))
281 / function (host) return prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module); end;
282 if module and mm.get_module("*", module) then
289 function def_env.module:load(name, hosts, config)
290 local mm = require "modulemanager";
292 hosts = get_hosts_set(hosts);
294 -- Load the module for each host
295 local ok, err, count, mod = true, nil, 0, nil;
297 if (not mm.is_loaded(host, name)) then
298 mod, err = mm.load(host, name, config);
301 if err == "global-module-already-loaded" then
303 ok, err, count = true, nil, 1;
307 self.session.print(err or "Unknown error loading module");
310 self.session.print("Loaded for "..mod.module.host);
315 return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
318 function def_env.module:unload(name, hosts)
319 local mm = require "modulemanager";
321 hosts = get_hosts_set(hosts, name);
323 -- Unload the module for each host
324 local ok, err, count = true, nil, 0;
326 if mm.is_loaded(host, name) then
327 ok, err = mm.unload(host, name);
330 self.session.print(err or "Unknown error unloading module");
333 self.session.print("Unloaded from "..host);
337 return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
340 function def_env.module:reload(name, hosts)
341 local mm = require "modulemanager";
343 hosts = array.collect(get_hosts_set(hosts, name)):sort(function (a, b)
344 if a == "*" then return true
345 elseif b == "*" then return false
346 else return a < b; end
349 -- Reload the module for each host
350 local ok, err, count = true, nil, 0;
351 for _, host in ipairs(hosts) do
352 if mm.is_loaded(host, name) then
353 ok, err = mm.reload(host, name);
356 self.session.print(err or "Unknown error reloading module");
362 self.session.print("Reloaded on "..host);
366 return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
369 function def_env.module:list(hosts)
371 hosts = array.collect(keys(prosody.hosts));
372 table.insert(hosts, 1, "*");
374 if type(hosts) == "string" then
377 if type(hosts) ~= "table" then
378 return false, "Please supply a host or a list of hosts you would like to see";
381 local print = self.session.print;
382 for _, host in ipairs(hosts) do
383 print((host == "*" and "Global" or host)..":");
384 local modules = array.collect(keys(modulemanager.get_modules(host) or {})):sort();
385 if #modules == 0 then
386 if prosody.hosts[host] then
387 print(" No modules loaded");
389 print(" Host not found");
392 for _, name in ipairs(modules) do
400 function def_env.config:load(filename, format)
401 local config_load = require "core.configmanager".load;
402 local ok, err = config_load(filename, format);
404 return false, err or "Unknown error loading config";
406 return true, "Config loaded";
409 function def_env.config:get(host, section, key)
410 local config_get = require "core.configmanager".get
411 return true, tostring(config_get(host, section, key));
414 function def_env.config:reload()
415 local ok, err = prosody.reload_config();
416 return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
420 function def_env.hosts:list()
421 for host, host_session in pairs(hosts) do
422 self.session.print(host);
427 function def_env.hosts:add(name)
432 local function show_c2s(callback)
433 for hostname, host in pairs(hosts) do
434 for username, user in pairs(host.sessions or {}) do
435 for resource, session in pairs(user.sessions or {}) do
436 local jid = username.."@"..hostname.."/"..resource;
437 callback(jid, session);
443 function def_env.c2s:show(match_jid)
444 local print, count = self.session.print, 0;
446 show_c2s(function (jid, session)
447 if curr_host ~= session.host then
448 curr_host = session.host;
451 if (not match_jid) or jid:match(match_jid) then
453 local status, priority = "unavailable", tostring(session.priority or "-");
454 if session.presence then
455 status = session.presence:child_with_name("show");
457 status = status:get_text() or "[invalid!]";
459 status = "available";
462 print(" "..jid.." - "..status.."("..priority..")");
465 return true, "Total: "..count.." clients";
468 function def_env.c2s:show_insecure(match_jid)
469 local print, count = self.session.print, 0;
470 show_c2s(function (jid, session)
471 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
476 return true, "Total: "..count.." insecure client connections";
479 function def_env.c2s:show_secure(match_jid)
480 local print, count = self.session.print, 0;
481 show_c2s(function (jid, session)
482 if ((not match_jid) or jid:match(match_jid)) and session.secure then
487 return true, "Total: "..count.." secure client connections";
490 function def_env.c2s:close(match_jid)
491 local print, count = self.session.print, 0;
492 show_c2s(function (jid, session)
493 if jid == match_jid or jid_bare(jid) == match_jid then
498 return true, "Total: "..count.." sessions closed";
501 local function session_flags(session, line)
502 if session.cert_identity_status == "valid" then
503 line[#line+1] = "(secure)";
504 elseif session.secure then
505 line[#line+1] = "(encrypted)";
507 if session.compressed then
508 line[#line+1] = "(compressed)";
510 if session.smacks then
511 line[#line+1] = "(sm)";
513 if session.conn and session.conn:ip():match(":") then
514 line[#line+1] = "(IPv6)";
516 return table.concat(line, " ");
520 function def_env.s2s:show(match_jid)
521 local _print = self.session.print;
522 local print = self.session.print;
524 local count_in, count_out = 0,0;
526 for host, host_session in pairs(hosts) do
527 print = function (...) _print(host); _print(...); print = _print; end
528 for remotehost, session in pairs(host_session.s2sout) do
529 if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
530 count_out = count_out + 1;
531 print(session_flags(session, {" ", host, "->", remotehost}));
532 if session.sendq then
533 print(" There are "..#session.sendq.." queued outgoing stanzas for this connection");
535 if session.type == "s2sout_unauthed" then
536 if session.connecting then
537 print(" Connection not yet established");
538 if not session.srv_hosts then
539 if not session.conn then
540 print(" We do not yet have a DNS answer for this host's SRV records");
542 print(" This host has no SRV records, using A record instead");
544 elseif session.srv_choice then
545 print(" We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
546 local srv_choice = session.srv_hosts[session.srv_choice];
547 print(" Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
549 elseif session.notopen then
550 print(" The <stream> has not yet been opened");
551 elseif not session.dialback_key then
552 print(" Dialback has not been initiated yet");
553 elseif session.dialback_key then
554 print(" Dialback has been requested, but no result received");
559 local subhost_filter = function (h)
560 return (match_jid and h:match(match_jid));
562 for session in pairs(incoming_s2s) do
563 if session.to_host == host and ((not match_jid) or host:match(match_jid)
564 or (session.from_host and session.from_host:match(match_jid))
565 -- Pft! is what I say to list comprehensions
566 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
567 count_in = count_in + 1;
568 print(session_flags(session, {" ", host, "<-", session.from_host or "(unknown)"}));
569 if session.type == "s2sin_unauthed" then
570 print(" Connection not yet authenticated");
572 for name in pairs(session.hosts) do
573 if name ~= session.from_host then
574 print(" also hosts "..tostring(name));
583 for session in pairs(incoming_s2s) do
584 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
585 count_in = count_in + 1;
586 print("Other incoming s2s connections");
587 print(" (unknown) <- "..(session.from_host or "(unknown)"));
591 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
594 local function print_subject(print, subject)
595 for _, entry in ipairs(subject) do
598 entry.name or entry.oid,
599 entry.value:gsub("[\r\n%z%c]", " ")
605 -- As much as it pains me to use the 0-based depths that OpenSSL does,
606 -- I think there's going to be more confusion among operators if we
608 local function print_errors(print, errors)
609 for depth, t in ipairs(errors) do
613 table.concat(t, "\n| ")
619 function def_env.s2s:showcert(domain)
620 local ser = require "util.serialization".serialize;
621 local print = self.session.print;
622 local domain_sessions = set.new(array.collect(keys(incoming_s2s)))
623 /function(session) return session.from_host == domain; end;
624 for local_host in values(prosody.hosts) do
625 local s2sout = local_host.s2sout;
626 if s2sout and s2sout[domain] then
627 domain_sessions:add(s2sout[domain]);
631 for session in domain_sessions do
632 local conn = session.conn;
633 conn = conn and conn:socket();
634 if not conn.getpeerchain then
635 if conn.dohandshake then
636 error("This version of LuaSec does not support certificate viewing");
639 local certs = conn:getpeerchain();
640 local cert = certs[1];
642 local digest = cert:digest("sha1");
643 if not cert_set[digest] then
644 local chain_valid, chain_errors = conn:getpeerverification();
647 from = session.from_host,
648 to = session.to_host,
649 direction = session.direction
651 chain_valid = chain_valid;
652 chain_errors = chain_errors;
656 table.insert(cert_set[digest], {
657 from = session.from_host,
658 to = session.to_host,
659 direction = session.direction
665 local domain_certs = array.collect(values(cert_set));
666 -- Phew. We now have a array of unique certificates presented by domain.
667 local print = self.session.print;
668 local n_certs = #domain_certs;
671 return "No certificates found for "..domain;
674 local function _capitalize_and_colon(byte)
675 return string.upper(byte)..":";
677 local function pretty_fingerprint(hash)
678 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
681 for cert_info in values(domain_certs) do
682 local certs = cert_info.certs;
683 local cert = certs[1];
685 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
687 local n_streams = #cert_info;
688 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
689 for _, stream in ipairs(cert_info) do
690 if stream.direction == "incoming" then
691 print(" "..stream.to.." <- "..stream.from);
693 print(" "..stream.from.." -> "..stream.to);
697 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
698 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
700 print("Trusted certificate: Yes");
702 print("Trusted certificate: No");
703 print_errors(print, errors);
707 print_subject(print, cert:issuer());
709 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
711 print_subject(print, cert:subject());
714 return ("Showing "..n_certs.." certificate"
715 ..(n_certs==1 and "" or "s")
716 .." presented by "..domain..".");
719 function def_env.s2s:close(from, to)
720 local print, count = self.session.print, 0;
722 if not (from and to) then
723 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
724 elseif from == to then
725 return false, "Both from and to are the same... you can't do that :)";
728 if hosts[from] and not hosts[to] then
729 -- Is an outgoing connection
730 local session = hosts[from].s2sout[to];
732 print("No outgoing connection from "..from.." to "..to)
734 (session.close or s2smanager.destroy_session)(session);
736 print("Closed outgoing session from "..from.." to "..to);
738 elseif hosts[to] and not hosts[from] then
739 -- Is an incoming connection
740 for session in pairs(incoming_s2s) do
741 if session.to_host == to and session.from_host == from then
742 (session.close or s2smanager.destroy_session)(session);
748 print("No incoming connections from "..from.." to "..to);
750 print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
752 elseif hosts[to] and hosts[from] then
753 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
755 return false, "Neither of the hostnames you specified are being used on this server";
758 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
761 def_env.host = {}; def_env.hosts = def_env.host;
763 function def_env.host:activate(hostname, config)
764 return hostmanager.activate(hostname, config);
766 function def_env.host:deactivate(hostname, reason)
767 return hostmanager.deactivate(hostname, reason);
770 function def_env.host:list()
771 local print = self.session.print;
773 for host in values(array.collect(keys(prosody.hosts)):sort()) do
777 return true, i.." hosts";
782 function def_env.port:list()
783 local print = self.session.print;
784 local services = portmanager.get_active_services().data;
785 local ordered_services, n_ports = {}, 0;
786 for service, interfaces in pairs(services) do
787 table.insert(ordered_services, service);
789 table.sort(ordered_services);
790 for _, service in ipairs(ordered_services) do
791 local ports_list = {};
792 for interface, ports in pairs(services[service]) do
793 for port in pairs(ports) do
794 table.insert(ports_list, "["..interface.."]:"..port);
797 n_ports = n_ports + #ports_list;
798 print(service..": "..table.concat(ports_list, ", "));
800 return true, #ordered_services.." services listening on "..n_ports.." ports";
803 function def_env.port:close(close_port, close_interface)
804 close_port = assert(tonumber(close_port), "Invalid port number");
806 local services = portmanager.get_active_services().data;
807 for service, interfaces in pairs(services) do
808 for interface, ports in pairs(interfaces) do
809 if not close_interface or close_interface == interface then
810 if ports[close_port] then
811 self.session.print("Closing ["..interface.."]:"..close_port.."...");
812 local ok, err = portmanager.close(interface, close_port)
814 self.session.print("Failed to close "..interface.." "..port..": "..err);
816 n_closed = n_closed + 1;
822 return true, "Closed "..n_closed.." ports";
827 function printbanner(session)
828 local option = config.get("*", "core", "console_banner");
829 if option == nil or option == "full" or option == "graphic" then
832 | _ \ _ __ ___ ___ _-_ __| |_ _
833 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
834 | __/| | | (_) \__ \ |_| | (_| | |_| |
835 |_| |_| \___/|___/\___/ \__,_|\__, |
836 A study in simplicity |___/
840 if option == nil or option == "short" or option == "full" then
841 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
842 session.print("You may find more help on using this console in our online documentation at ");
843 session.print("http://prosody.im/doc/console\n");
845 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
846 if type(option) == "string" then
847 session.print(option)
848 elseif type(option) == "function" then
849 setfenv(option, redirect_output(_G, session));
850 pcall(option, session);
855 module:add_item("net-provider", {
857 listener = console_listener;