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:count(match_jid)
445 show_c2s(function (jid, session)
446 if (not match_jid) or jid:match(match_jid) then
450 return true, "Total: "..count.." clients";
453 function def_env.c2s:show(match_jid)
454 local print, count = self.session.print, 0;
456 show_c2s(function (jid, session)
457 if curr_host ~= session.host then
458 curr_host = session.host;
461 if (not match_jid) or jid:match(match_jid) then
463 local status, priority = "unavailable", tostring(session.priority or "-");
464 if session.presence then
465 status = session.presence:child_with_name("show");
467 status = status:get_text() or "[invalid!]";
469 status = "available";
472 print(" "..jid.." - "..status.."("..priority..")");
475 return true, "Total: "..count.." clients";
478 function def_env.c2s:show_insecure(match_jid)
479 local print, count = self.session.print, 0;
480 show_c2s(function (jid, session)
481 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
486 return true, "Total: "..count.." insecure client connections";
489 function def_env.c2s:show_secure(match_jid)
490 local print, count = self.session.print, 0;
491 show_c2s(function (jid, session)
492 if ((not match_jid) or jid:match(match_jid)) and session.secure then
497 return true, "Total: "..count.." secure client connections";
500 function def_env.c2s:close(match_jid)
501 local print, count = self.session.print, 0;
502 show_c2s(function (jid, session)
503 if jid == match_jid or jid_bare(jid) == match_jid then
508 return true, "Total: "..count.." sessions closed";
511 local function session_flags(session, line)
512 if session.cert_identity_status == "valid" then
513 line[#line+1] = "(secure)";
514 elseif session.secure then
515 line[#line+1] = "(encrypted)";
517 if session.compressed then
518 line[#line+1] = "(compressed)";
520 if session.smacks then
521 line[#line+1] = "(sm)";
523 if session.conn and session.conn:ip():match(":") then
524 line[#line+1] = "(IPv6)";
526 return table.concat(line, " ");
530 function def_env.s2s:show(match_jid)
531 local _print = self.session.print;
532 local print = self.session.print;
534 local count_in, count_out = 0,0;
536 for host, host_session in pairs(hosts) do
537 print = function (...) _print(host); _print(...); print = _print; end
538 for remotehost, session in pairs(host_session.s2sout) do
539 if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
540 count_out = count_out + 1;
541 print(session_flags(session, {" ", host, "->", remotehost}));
542 if session.sendq then
543 print(" There are "..#session.sendq.." queued outgoing stanzas for this connection");
545 if session.type == "s2sout_unauthed" then
546 if session.connecting then
547 print(" Connection not yet established");
548 if not session.srv_hosts then
549 if not session.conn then
550 print(" We do not yet have a DNS answer for this host's SRV records");
552 print(" This host has no SRV records, using A record instead");
554 elseif session.srv_choice then
555 print(" We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
556 local srv_choice = session.srv_hosts[session.srv_choice];
557 print(" Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
559 elseif session.notopen then
560 print(" The <stream> has not yet been opened");
561 elseif not session.dialback_key then
562 print(" Dialback has not been initiated yet");
563 elseif session.dialback_key then
564 print(" Dialback has been requested, but no result received");
569 local subhost_filter = function (h)
570 return (match_jid and h:match(match_jid));
572 for session in pairs(incoming_s2s) do
573 if session.to_host == host and ((not match_jid) or host:match(match_jid)
574 or (session.from_host and session.from_host:match(match_jid))
575 -- Pft! is what I say to list comprehensions
576 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
577 count_in = count_in + 1;
578 print(session_flags(session, {" ", host, "<-", session.from_host or "(unknown)"}));
579 if session.type == "s2sin_unauthed" then
580 print(" Connection not yet authenticated");
582 for name in pairs(session.hosts) do
583 if name ~= session.from_host then
584 print(" also hosts "..tostring(name));
593 for session in pairs(incoming_s2s) do
594 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
595 count_in = count_in + 1;
596 print("Other incoming s2s connections");
597 print(" (unknown) <- "..(session.from_host or "(unknown)"));
601 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
604 local function print_subject(print, subject)
605 for _, entry in ipairs(subject) do
608 entry.name or entry.oid,
609 entry.value:gsub("[\r\n%z%c]", " ")
615 -- As much as it pains me to use the 0-based depths that OpenSSL does,
616 -- I think there's going to be more confusion among operators if we
618 local function print_errors(print, errors)
619 for depth, t in ipairs(errors) do
623 table.concat(t, "\n| ")
629 function def_env.s2s:showcert(domain)
630 local ser = require "util.serialization".serialize;
631 local print = self.session.print;
632 local domain_sessions = set.new(array.collect(keys(incoming_s2s)))
633 /function(session) return session.from_host == domain; end;
634 for local_host in values(prosody.hosts) do
635 local s2sout = local_host.s2sout;
636 if s2sout and s2sout[domain] then
637 domain_sessions:add(s2sout[domain]);
641 for session in domain_sessions do
642 local conn = session.conn;
643 conn = conn and conn:socket();
644 if not conn.getpeerchain then
645 if conn.dohandshake then
646 error("This version of LuaSec does not support certificate viewing");
649 local certs = conn:getpeerchain();
650 local cert = certs[1];
652 local digest = cert:digest("sha1");
653 if not cert_set[digest] then
654 local chain_valid, chain_errors = conn:getpeerverification();
657 from = session.from_host,
658 to = session.to_host,
659 direction = session.direction
661 chain_valid = chain_valid;
662 chain_errors = chain_errors;
666 table.insert(cert_set[digest], {
667 from = session.from_host,
668 to = session.to_host,
669 direction = session.direction
675 local domain_certs = array.collect(values(cert_set));
676 -- Phew. We now have a array of unique certificates presented by domain.
677 local print = self.session.print;
678 local n_certs = #domain_certs;
681 return "No certificates found for "..domain;
684 local function _capitalize_and_colon(byte)
685 return string.upper(byte)..":";
687 local function pretty_fingerprint(hash)
688 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
691 for cert_info in values(domain_certs) do
692 local certs = cert_info.certs;
693 local cert = certs[1];
695 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
697 local n_streams = #cert_info;
698 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
699 for _, stream in ipairs(cert_info) do
700 if stream.direction == "incoming" then
701 print(" "..stream.to.." <- "..stream.from);
703 print(" "..stream.from.." -> "..stream.to);
707 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
708 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
710 print("Trusted certificate: Yes");
712 print("Trusted certificate: No");
713 print_errors(print, errors);
717 print_subject(print, cert:issuer());
719 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
721 print_subject(print, cert:subject());
724 return ("Showing "..n_certs.." certificate"
725 ..(n_certs==1 and "" or "s")
726 .." presented by "..domain..".");
729 function def_env.s2s:close(from, to)
730 local print, count = self.session.print, 0;
732 if not (from and to) then
733 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
734 elseif from == to then
735 return false, "Both from and to are the same... you can't do that :)";
738 if hosts[from] and not hosts[to] then
739 -- Is an outgoing connection
740 local session = hosts[from].s2sout[to];
742 print("No outgoing connection from "..from.." to "..to)
744 (session.close or s2smanager.destroy_session)(session);
746 print("Closed outgoing session from "..from.." to "..to);
748 elseif hosts[to] and not hosts[from] then
749 -- Is an incoming connection
750 for session in pairs(incoming_s2s) do
751 if session.to_host == to and session.from_host == from then
752 (session.close or s2smanager.destroy_session)(session);
758 print("No incoming connections from "..from.." to "..to);
760 print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
762 elseif hosts[to] and hosts[from] then
763 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
765 return false, "Neither of the hostnames you specified are being used on this server";
768 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
771 def_env.host = {}; def_env.hosts = def_env.host;
773 function def_env.host:activate(hostname, config)
774 return hostmanager.activate(hostname, config);
776 function def_env.host:deactivate(hostname, reason)
777 return hostmanager.deactivate(hostname, reason);
780 function def_env.host:list()
781 local print = self.session.print;
783 for host in values(array.collect(keys(prosody.hosts)):sort()) do
787 return true, i.." hosts";
792 function def_env.port:list()
793 local print = self.session.print;
794 local services = portmanager.get_active_services().data;
795 local ordered_services, n_ports = {}, 0;
796 for service, interfaces in pairs(services) do
797 table.insert(ordered_services, service);
799 table.sort(ordered_services);
800 for _, service in ipairs(ordered_services) do
801 local ports_list = {};
802 for interface, ports in pairs(services[service]) do
803 for port in pairs(ports) do
804 table.insert(ports_list, "["..interface.."]:"..port);
807 n_ports = n_ports + #ports_list;
808 print(service..": "..table.concat(ports_list, ", "));
810 return true, #ordered_services.." services listening on "..n_ports.." ports";
813 function def_env.port:close(close_port, close_interface)
814 close_port = assert(tonumber(close_port), "Invalid port number");
816 local services = portmanager.get_active_services().data;
817 for service, interfaces in pairs(services) do
818 for interface, ports in pairs(interfaces) do
819 if not close_interface or close_interface == interface then
820 if ports[close_port] then
821 self.session.print("Closing ["..interface.."]:"..close_port.."...");
822 local ok, err = portmanager.close(interface, close_port)
824 self.session.print("Failed to close "..interface.." "..port..": "..err);
826 n_closed = n_closed + 1;
832 return true, "Closed "..n_closed.." ports";
837 function printbanner(session)
838 local option = config.get("*", "core", "console_banner");
839 if option == nil or option == "full" or option == "graphic" then
842 | _ \ _ __ ___ ___ _-_ __| |_ _
843 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
844 | __/| | | (_) \__ \ |_| | (_| | |_| |
845 |_| |_| \___/|___/\___/ \__,_|\__, |
846 A study in simplicity |___/
850 if option == nil or option == "short" or option == "full" then
851 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
852 session.print("You may find more help on using this console in our online documentation at ");
853 session.print("http://prosody.im/doc/console\n");
855 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
856 if type(option) == "string" then
857 session.print(option)
858 elseif type(option) == "function" then
859 setfenv(option, redirect_output(_G, session));
860 pcall(option, session);
865 module:add_item("net-provider", {
867 listener = console_listener;