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.
11 local hostmanager = require "core.hostmanager";
12 local modulemanager = require "core.modulemanager";
13 local s2smanager = require "core.s2smanager";
14 local portmanager = require "core.portmanager";
18 local prosody = _G.prosody;
19 local hosts = prosody.hosts;
20 local incoming_s2s = prosody.incoming_s2s;
22 local console_listener = { default_port = 5582; default_mode = "*a"; interface = "127.0.0.1" };
24 local iterators = require "util.iterators";
25 local keys, values = iterators.keys, iterators.values;
26 local jid_bare, jid_split = import("util.jid", "bare", "prepped_split");
27 local set, array = require "util.set", require "util.array";
28 local cert_verify_identity = require "util.x509".verify_identity;
29 local envload = require "util.envload".envload;
30 local envloadfile = require "util.envload".envloadfile;
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;
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
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 (...)
55 for i=1,select("#", ...) do
56 t[i] = tostring(select(i, ...));
58 w("| "..table.concat(t, "\t").."\n");
60 disconnect = function () conn:close(); end;
62 session.env = setmetatable({}, default_env_mt);
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 });
74 function console:process_line(session, line)
77 if line:match("^>") then
78 line = line:gsub("^>", "");
80 elseif line == "\004" then
81 commands["bye"](session, line);
84 local command = line:match("^%w+") or line:match("%p");
85 if commands[command] then
86 commands[command](session, line);
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);
97 chunk, err = envload(line, chunkname, env);
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);
107 local ranok, taskok, message = pcall(chunk);
109 if not (ranok or message or useglobalenv) and commands[line:lower()] then
110 commands[line:lower()](session, line);
115 session.print("Fatal error while running command, it did not complete");
116 session.print("Error: "..taskok);
121 session.print("Result: "..tostring(taskok));
123 elseif (not taskok) and message then
124 session.print("Command completed with a problem");
125 session.print("Message: "..tostring(message));
129 session.print("OK: "..tostring(message));
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));
142 function console_listener.onincoming(conn, data)
143 local session = sessions[conn];
145 local partial = session.partial_data;
147 data = partial..data;
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));
155 session.partial_data = data:match("[^\n]+$");
158 function console_listener.ondisconnect(conn, err)
159 local session = sessions[conn];
161 session.disconnect();
162 sessions[conn] = nil;
166 function console_listener.ondetach(conn)
167 sessions[conn] = nil;
170 -- Console commands --
171 -- These are simple commands, not valid standalone in Lua
173 function commands.bye(session)
174 session.print("See you! :)");
175 session.closed = true;
176 session.disconnect();
178 commands.quit, commands.exit = commands.bye, commands.bye;
180 commands["!"] = function (session, data)
181 if data:match("^!!") and session.env._ then
182 session.print("!> "..session.env._);
183 return console_listener.onincoming(session.conn, session.env._);
185 local old, new = data:match("^!(.-[^\\])!(.-)!$");
187 local ok, res = pcall(string.gsub, session.env._, old, new);
192 session.print("!> "..res);
193 return console_listener.onincoming(session.conn, res);
195 session.print("Sorry, not sure what you want");
199 function commands.help(session, data)
200 local print = session.print;
201 local section = data:match("^help (%w+)");
203 print [[Commands are divided into multiple sections. For help on a particular section, ]]
204 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
206 print [[c2s - Commands to manage local client-to-server sessions]]
207 print [[s2s - Commands to manage sessions between this server and others]]
208 print [[module - Commands to load/reload/unload modules/plugins]]
209 print [[host - Commands to activate, deactivate and list virtual hosts]]
210 print [[user - Commands to create and delete users, and change their passwords]]
211 print [[server - Uptime, version, shutting down, etc.]]
212 print [[port - Commands to manage ports the server is listening on]]
213 print [[dns - Commands to manage and inspect the internal DNS resolver]]
214 print [[config - Reloading the configuration, etc.]]
215 print [[console - Help regarding the console itself]]
216 elseif section == "c2s" then
217 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
218 print [[c2s:show_insecure() - Show all unencrypted client connections]]
219 print [[c2s:show_secure() - Show all encrypted client connections]]
220 print [[c2s:close(jid) - Close all sessions for the specified JID]]
221 elseif section == "s2s" then
222 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
223 print [[s2s:close(from, to) - Close a connection from one domain to another]]
224 print [[s2s:closeall(host) - Close all the incoming/outgoing s2s sessions to specified host]]
225 elseif section == "module" then
226 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
227 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
228 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
229 print [[module:list(host) - List the modules loaded on the specified host]]
230 elseif section == "host" then
231 print [[host:activate(hostname) - Activates the specified host]]
232 print [[host:deactivate(hostname) - Disconnects all clients on this host and deactivates]]
233 print [[host:list() - List the currently-activated hosts]]
234 elseif section == "user" then
235 print [[user:create(jid, password) - Create the specified user account]]
236 print [[user:password(jid, password) - Set the password for the specified user account]]
237 print [[user:delete(jid) - Permanently remove the specified user account]]
238 print [[user:list(hostname, pattern) - List users on the specified host, optionally filtering with a pattern]]
239 elseif section == "server" then
240 print [[server:version() - Show the server's version number]]
241 print [[server:uptime() - Show how long the server has been running]]
242 print [[server:memory() - Show details about the server's memory usage]]
243 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
244 elseif section == "port" then
245 print [[port:list() - Lists all network ports prosody currently listens on]]
246 print [[port:close(port, interface) - Close a port]]
247 elseif section == "dns" then
248 print [[dns:lookup(name, type, class) - Do a DNS lookup]]
249 print [[dns:addnameserver(nameserver) - Add a nameserver to the list]]
250 print [[dns:setnameserver(nameserver) - Replace the list of name servers with the supplied one]]
251 print [[dns:purge() - Clear the DNS cache]]
252 print [[dns:cache() - Show cached records]]
253 elseif section == "config" then
254 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
255 elseif section == "console" then
256 print [[Hey! Welcome to Prosody's admin console.]]
257 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
258 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
259 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
261 print [[For now we offer a couple of handy shortcuts:]]
262 print [[!! - Repeat the last command]]
263 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
265 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
266 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
267 print [[the running server. Great fun, but be careful not to break anything :)]]
272 -- Session environment --
273 -- Anything in def_env will be accessible within the session as a global variable
277 function def_env.server:insane_reload()
278 prosody.unlock_globals();
280 prosody = _G.prosody;
281 return true, "Server reloaded";
284 function def_env.server:version()
285 return true, tostring(prosody.version or "unknown");
288 function def_env.server:uptime()
289 local t = os.time()-prosody.start_time;
290 local seconds = t%60;
291 t = (t - seconds)/60;
292 local minutes = t%60;
293 t = (t - minutes)/60;
297 return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
298 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
299 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
302 function def_env.server:shutdown(reason)
303 prosody.shutdown(reason);
304 return true, "Shutdown initiated";
307 local function human(kb)
310 kb, unit = kb/1024, "M";
312 return ("%0.2f%sB"):format(kb, unit);
315 function def_env.server:memory()
316 local pposix = require("util.pposix");
317 if not pposix.meminfo then
318 return true, "Lua is using "..collectgarbage("count");
320 local mem, lua_mem = pposix.meminfo(), collectgarbage("count");
321 local print = self.session.print;
322 print("Process: "..human((mem.allocated+mem.allocated_mmap)/1024));
323 print(" Used: "..human(mem.used/1024).." ("..human(lua_mem).." by Lua)");
324 print(" Free: "..human(mem.unused/1024).." ("..human(mem.returnable/1024).." returnable)");
330 local function get_hosts_set(hosts, module)
331 if type(hosts) == "table" then
333 return set.new(hosts);
334 elseif hosts._items then
337 elseif type(hosts) == "string" then
338 return set.new { hosts };
339 elseif hosts == nil then
340 local mm = require "modulemanager";
341 local hosts_set = set.new(array.collect(keys(prosody.hosts)))
342 / function (host) return (prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module)) and host or nil; end;
343 if module and mm.get_module("*", module) then
350 function def_env.module:load(name, hosts, config)
351 local mm = require "modulemanager";
353 hosts = get_hosts_set(hosts);
355 -- Load the module for each host
356 local ok, err, count, mod = true, nil, 0, nil;
358 if (not mm.is_loaded(host, name)) then
359 mod, err = mm.load(host, name, config);
362 if err == "global-module-already-loaded" then
364 ok, err, count = true, nil, 1;
368 self.session.print(err or "Unknown error loading module");
371 self.session.print("Loaded for "..mod.module.host);
376 return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
379 function def_env.module:unload(name, hosts)
380 local mm = require "modulemanager";
382 hosts = get_hosts_set(hosts, name);
384 -- Unload the module for each host
385 local ok, err, count = true, nil, 0;
387 if mm.is_loaded(host, name) then
388 ok, err = mm.unload(host, name);
391 self.session.print(err or "Unknown error unloading module");
394 self.session.print("Unloaded from "..host);
398 return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
401 function def_env.module:reload(name, hosts)
402 local mm = require "modulemanager";
404 hosts = array.collect(get_hosts_set(hosts, name)):sort(function (a, b)
405 if a == "*" then return true
406 elseif b == "*" then return false
407 else return a < b; end
410 -- Reload the module for each host
411 local ok, err, count = true, nil, 0;
412 for _, host in ipairs(hosts) do
413 if mm.is_loaded(host, name) then
414 ok, err = mm.reload(host, name);
417 self.session.print(err or "Unknown error reloading module");
423 self.session.print("Reloaded on "..host);
427 return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
430 function def_env.module:list(hosts)
432 hosts = array.collect(keys(prosody.hosts));
433 table.insert(hosts, 1, "*");
435 if type(hosts) == "string" then
438 if type(hosts) ~= "table" then
439 return false, "Please supply a host or a list of hosts you would like to see";
442 local print = self.session.print;
443 for _, host in ipairs(hosts) do
444 print((host == "*" and "Global" or host)..":");
445 local modules = array.collect(keys(modulemanager.get_modules(host) or {})):sort();
446 if #modules == 0 then
447 if prosody.hosts[host] then
448 print(" No modules loaded");
450 print(" Host not found");
453 for _, name in ipairs(modules) do
461 function def_env.config:load(filename, format)
462 local config_load = require "core.configmanager".load;
463 local ok, err = config_load(filename, format);
465 return false, err or "Unknown error loading config";
467 return true, "Config loaded";
470 function def_env.config:get(host, section, key)
471 local config_get = require "core.configmanager".get
472 return true, tostring(config_get(host, section, key));
475 function def_env.config:reload()
476 local ok, err = prosody.reload_config();
477 return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
481 function def_env.hosts:list()
482 for host, host_session in pairs(hosts) do
483 self.session.print(host);
488 function def_env.hosts:add(name)
493 local function show_c2s(callback)
494 for hostname, host in pairs(hosts) do
495 for username, user in pairs(host.sessions or {}) do
496 for resource, session in pairs(user.sessions or {}) do
497 local jid = username.."@"..hostname.."/"..resource;
498 callback(jid, session);
504 function def_env.c2s:count(match_jid)
506 show_c2s(function (jid, session)
507 if (not match_jid) or jid:match(match_jid) then
511 return true, "Total: "..count.." clients";
514 function def_env.c2s:show(match_jid)
515 local print, count = self.session.print, 0;
517 show_c2s(function (jid, session)
518 if curr_host ~= session.host then
519 curr_host = session.host;
522 if (not match_jid) or jid:match(match_jid) then
524 local status, priority = "unavailable", tostring(session.priority or "-");
525 if session.presence then
526 status = session.presence:child_with_name("show");
528 status = status:get_text() or "[invalid!]";
530 status = "available";
533 print(" "..jid.." - "..status.."("..priority..")");
536 return true, "Total: "..count.." clients";
539 function def_env.c2s:show_insecure(match_jid)
540 local print, count = self.session.print, 0;
541 show_c2s(function (jid, session)
542 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
547 return true, "Total: "..count.." insecure client connections";
550 function def_env.c2s:show_secure(match_jid)
551 local print, count = self.session.print, 0;
552 show_c2s(function (jid, session)
553 if ((not match_jid) or jid:match(match_jid)) and session.secure then
558 return true, "Total: "..count.." secure client connections";
561 function def_env.c2s:close(match_jid)
563 show_c2s(function (jid, session)
564 if jid == match_jid or jid_bare(jid) == match_jid then
569 return true, "Total: "..count.." sessions closed";
572 local function session_flags(session, line)
573 if session.cert_identity_status == "valid" then
574 line[#line+1] = "(secure)";
575 elseif session.secure then
576 line[#line+1] = "(encrypted)";
578 if session.compressed then
579 line[#line+1] = "(compressed)";
581 if session.smacks then
582 line[#line+1] = "(sm)";
584 if session.conn and session.conn:ip():match(":") then
585 line[#line+1] = "(IPv6)";
587 return table.concat(line, " ");
591 function def_env.s2s:show(match_jid)
592 local _print = self.session.print;
593 local print = self.session.print;
595 local count_in, count_out = 0,0;
597 for host, host_session in pairs(hosts) do
598 print = function (...) _print(host); _print(...); print = _print; end
599 for remotehost, session in pairs(host_session.s2sout) do
600 if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
601 count_out = count_out + 1;
602 print(session_flags(session, {" ", host, "->", remotehost}));
603 if session.sendq then
604 print(" There are "..#session.sendq.." queued outgoing stanzas for this connection");
606 if session.type == "s2sout_unauthed" then
607 if session.connecting then
608 print(" Connection not yet established");
609 if not session.srv_hosts then
610 if not session.conn then
611 print(" We do not yet have a DNS answer for this host's SRV records");
613 print(" This host has no SRV records, using A record instead");
615 elseif session.srv_choice then
616 print(" We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
617 local srv_choice = session.srv_hosts[session.srv_choice];
618 print(" Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
620 elseif session.notopen then
621 print(" The <stream> has not yet been opened");
622 elseif not session.dialback_key then
623 print(" Dialback has not been initiated yet");
624 elseif session.dialback_key then
625 print(" Dialback has been requested, but no result received");
630 local subhost_filter = function (h)
631 return (match_jid and h:match(match_jid));
633 for session in pairs(incoming_s2s) do
634 if session.to_host == host and ((not match_jid) or host:match(match_jid)
635 or (session.from_host and session.from_host:match(match_jid))
636 -- Pft! is what I say to list comprehensions
637 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
638 count_in = count_in + 1;
639 print(session_flags(session, {" ", host, "<-", session.from_host or "(unknown)"}));
640 if session.type == "s2sin_unauthed" then
641 print(" Connection not yet authenticated");
643 for name in pairs(session.hosts) do
644 if name ~= session.from_host then
645 print(" also hosts "..tostring(name));
654 for session in pairs(incoming_s2s) do
655 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
656 count_in = count_in + 1;
657 print("Other incoming s2s connections");
658 print(" (unknown) <- "..(session.from_host or "(unknown)"));
662 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
665 local function print_subject(print, subject)
666 for _, entry in ipairs(subject) do
669 entry.name or entry.oid,
670 entry.value:gsub("[\r\n%z%c]", " ")
676 -- As much as it pains me to use the 0-based depths that OpenSSL does,
677 -- I think there's going to be more confusion among operators if we
679 local function print_errors(print, errors)
680 for depth, t in pairs(errors) do
684 table.concat(t, "\n| ")
690 function def_env.s2s:showcert(domain)
691 local ser = require "util.serialization".serialize;
692 local print = self.session.print;
693 local domain_sessions = set.new(array.collect(keys(incoming_s2s)))
694 /function(session) return session.from_host == domain and session or nil; end;
695 for local_host in values(prosody.hosts) do
696 local s2sout = local_host.s2sout;
697 if s2sout and s2sout[domain] then
698 domain_sessions:add(s2sout[domain]);
702 for session in domain_sessions do
703 local conn = session.conn;
704 conn = conn and conn:socket();
705 if not conn.getpeerchain then
706 if conn.dohandshake then
707 error("This version of LuaSec does not support certificate viewing");
710 local cert = conn:getpeercertificate();
712 local certs = conn:getpeerchain();
713 local digest = cert:digest("sha1");
714 if not cert_set[digest] then
715 local chain_valid, chain_errors = conn:getpeerverification();
718 from = session.from_host,
719 to = session.to_host,
720 direction = session.direction
722 chain_valid = chain_valid;
723 chain_errors = chain_errors;
727 table.insert(cert_set[digest], {
728 from = session.from_host,
729 to = session.to_host,
730 direction = session.direction
736 local domain_certs = array.collect(values(cert_set));
737 -- Phew. We now have a array of unique certificates presented by domain.
738 local n_certs = #domain_certs;
741 return "No certificates found for "..domain;
744 local function _capitalize_and_colon(byte)
745 return string.upper(byte)..":";
747 local function pretty_fingerprint(hash)
748 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
751 for cert_info in values(domain_certs) do
752 local certs = cert_info.certs;
753 local cert = certs[1];
755 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
757 local n_streams = #cert_info;
758 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
759 for _, stream in ipairs(cert_info) do
760 if stream.direction == "incoming" then
761 print(" "..stream.to.." <- "..stream.from);
763 print(" "..stream.from.." -> "..stream.to);
767 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
768 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
770 print("Trusted certificate: Yes");
772 print("Trusted certificate: No");
773 print_errors(print, errors);
777 print_subject(print, cert:issuer());
779 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
781 print_subject(print, cert:subject());
784 return ("Showing "..n_certs.." certificate"
785 ..(n_certs==1 and "" or "s")
786 .." presented by "..domain..".");
789 function def_env.s2s:close(from, to)
790 local print, count = self.session.print, 0;
792 if not (from and to) then
793 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
794 elseif from == to then
795 return false, "Both from and to are the same... you can't do that :)";
798 if hosts[from] and not hosts[to] then
799 -- Is an outgoing connection
800 local session = hosts[from].s2sout[to];
802 print("No outgoing connection from "..from.." to "..to)
804 (session.close or s2smanager.destroy_session)(session);
806 print("Closed outgoing session from "..from.." to "..to);
808 elseif hosts[to] and not hosts[from] then
809 -- Is an incoming connection
810 for session in pairs(incoming_s2s) do
811 if session.to_host == to and session.from_host == from then
812 (session.close or s2smanager.destroy_session)(session);
818 print("No incoming connections from "..from.." to "..to);
820 print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
822 elseif hosts[to] and hosts[from] then
823 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
825 return false, "Neither of the hostnames you specified are being used on this server";
828 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
831 function def_env.s2s:closeall(host)
834 if not host or type(host) ~= "string" then return false, "wrong syntax: please use s2s:closeall('hostname.tld')"; end
836 for session in pairs(incoming_s2s) do
837 if session.to_host == host then
838 (session.close or s2smanager.destroy_session)(session);
842 for _, session in pairs(hosts[host].s2sout) do
843 (session.close or s2smanager.destroy_session)(session);
847 for session in pairs(incoming_s2s) do
848 if session.from_host == host then
849 (session.close or s2smanager.destroy_session)(session);
853 for _, h in pairs(hosts) do
854 if h.s2sout[host] then
855 (h.s2sout[host].close or s2smanager.destroy_session)(h.s2sout[host]);
861 if count == 0 then return false, "No sessions to close.";
862 else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
865 def_env.host = {}; def_env.hosts = def_env.host;
867 function def_env.host:activate(hostname, config)
868 return hostmanager.activate(hostname, config);
870 function def_env.host:deactivate(hostname, reason)
871 return hostmanager.deactivate(hostname, reason);
874 function def_env.host:list()
875 local print = self.session.print;
877 for host in values(array.collect(keys(prosody.hosts)):sort()) do
881 return true, i.." hosts";
886 function def_env.port:list()
887 local print = self.session.print;
888 local services = portmanager.get_active_services().data;
889 local ordered_services, n_ports = {}, 0;
890 for service, interfaces in pairs(services) do
891 table.insert(ordered_services, service);
893 table.sort(ordered_services);
894 for _, service in ipairs(ordered_services) do
895 local ports_list = {};
896 for interface, ports in pairs(services[service]) do
897 for port in pairs(ports) do
898 table.insert(ports_list, "["..interface.."]:"..port);
901 n_ports = n_ports + #ports_list;
902 print(service..": "..table.concat(ports_list, ", "));
904 return true, #ordered_services.." services listening on "..n_ports.." ports";
907 function def_env.port:close(close_port, close_interface)
908 close_port = assert(tonumber(close_port), "Invalid port number");
910 local services = portmanager.get_active_services().data;
911 for service, interfaces in pairs(services) do
912 for interface, ports in pairs(interfaces) do
913 if not close_interface or close_interface == interface then
914 if ports[close_port] then
915 self.session.print("Closing ["..interface.."]:"..close_port.."...");
916 local ok, err = portmanager.close(interface, close_port)
918 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
920 n_closed = n_closed + 1;
926 return true, "Closed "..n_closed.." ports";
931 local console_room_mt = {
932 __index = function (self, k) return self.room[k]; end;
933 __tostring = function (self)
934 return "MUC room <"..self.room.jid..">";
938 local function check_muc(jid)
939 local room_name, host = jid_split(jid);
940 if not hosts[host] then
941 return nil, "No such host: "..host;
942 elseif not hosts[host].modules.muc then
943 return nil, "Host '"..host.."' is not a MUC service";
945 return room_name, host;
948 function def_env.muc:create(room_jid)
949 local room, host = check_muc(room_jid);
950 if not room_name then
951 return room_name, host;
953 if not room then return nil, host end
954 if hosts[host].modules.muc.rooms[room_jid] then return nil, "Room exists already" end
955 return hosts[host].modules.muc.create_room(room_jid);
958 function def_env.muc:room(room_jid)
959 local room_name, host = check_muc(room_jid);
960 if not room_name then
961 return room_name, host;
963 local room_obj = hosts[host].modules.muc.rooms[room_jid];
965 return nil, "No such room: "..room_jid;
967 return setmetatable({ room = room_obj }, console_room_mt);
970 local um = require"core.usermanager";
973 function def_env.user:create(jid, password)
974 local username, host = jid_split(jid);
975 if not hosts[host] then
976 return nil, "No such host: "..host;
977 elseif um.user_exists(username, host) then
978 return nil, "User exists";
980 local ok, err = um.create_user(username, password, host);
982 return true, "User created";
984 return nil, "Could not create user: "..err;
988 function def_env.user:delete(jid)
989 local username, host = jid_split(jid);
990 if not hosts[host] then
991 return nil, "No such host: "..host;
992 elseif not um.user_exists(username, host) then
993 return nil, "No such user";
995 local ok, err = um.delete_user(username, host);
997 return true, "User deleted";
999 return nil, "Could not delete user: "..err;
1003 function def_env.user:password(jid, password)
1004 local username, host = jid_split(jid);
1005 if not hosts[host] then
1006 return nil, "No such host: "..host;
1007 elseif not um.user_exists(username, host) then
1008 return nil, "No such user";
1010 local ok, err = um.set_password(username, password, host);
1012 return true, "User password changed";
1014 return nil, "Could not change password for user: "..err;
1018 function def_env.user:list(host, pat)
1020 return nil, "No host given";
1021 elseif not hosts[host] then
1022 return nil, "No such host";
1024 local print = self.session.print;
1025 local total, matches = 0, 0;
1026 for user in um.users(host) do
1027 if not pat or user:match(pat) then
1028 print(user.."@"..host);
1029 matches = matches + 1;
1033 return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
1038 local st = require "util.stanza";
1039 function def_env.xmpp:ping(localhost, remotehost)
1040 if hosts[localhost] then
1041 core_post_stanza(hosts[localhost],
1042 st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
1043 :tag("ping", {xmlns="urn:xmpp:ping"}));
1044 return true, "Sent ping";
1046 return nil, "No such host";
1051 local adns = require"net.adns";
1052 local dns = require"net.dns";
1054 function def_env.dns:lookup(name, typ, class)
1055 local ret = "Query sent";
1056 local print = self.session.print;
1057 local function handler(...)
1058 ret = "Got response";
1061 adns.lookup(handler, name, typ, class);
1065 function def_env.dns:addnameserver(...)
1066 dns._resolver:addnameserver(...)
1070 function def_env.dns:setnameserver(...)
1071 dns._resolver:setnameserver(...)
1075 function def_env.dns:purge()
1080 function def_env.dns:cache()
1081 return true, "Cache:\n"..tostring(dns.cache())
1086 function def_env.http:list()
1087 local print = self.session.print;
1089 for host in pairs(prosody.hosts) do
1090 local http_apps = modulemanager.get_items("http-provider", host);
1091 if #http_apps > 0 then
1092 local http_host = module:context(host):get_option("http_host");
1093 print("HTTP endpoints on "..host..(http_host and (" (using "..http_host.."):") or ":"));
1094 for _, provider in ipairs(http_apps) do
1095 local url = module:context(host):http_url(provider.name);
1102 local default_host = module:get_option("http_default_host");
1103 if not default_host then
1104 print("HTTP requests to unknown hosts will return 404 Not Found");
1106 print("HTTP requests to unknown hosts will be handled by "..default_host);
1113 function printbanner(session)
1114 local option = module:get_option("console_banner");
1115 if option == nil or option == "full" or option == "graphic" then
1118 | _ \ _ __ ___ ___ _-_ __| |_ _
1119 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1120 | __/| | | (_) \__ \ |_| | (_| | |_| |
1121 |_| |_| \___/|___/\___/ \__,_|\__, |
1122 A study in simplicity |___/
1126 if option == nil or option == "short" or option == "full" then
1127 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1128 session.print("You may find more help on using this console in our online documentation at ");
1129 session.print("http://prosody.im/doc/console\n");
1131 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
1132 if type(option) == "string" then
1133 session.print(option)
1134 elseif type(option) == "function" then
1135 module:log("warn", "Using functions as value for the console_banner option is no longer supported");
1140 module:provides("net", {
1142 listener = console_listener;
1143 default_port = 5582;