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 = require "util.jid";
27 local jid_bare, jid_split = jid.bare, jid.split;
28 local set, array = require "util.set", require "util.array";
29 local cert_verify_identity = require "util.x509".verify_identity;
30 local envload = require "util.envload".envload;
31 local envloadfile = require "util.envload".envloadfile;
33 local commands = module:shared("commands")
34 local def_env = module:shared("env");
35 local default_env_mt = { __index = def_env };
36 local core_post_stanza = prosody.core_post_stanza;
38 local function redirect_output(_G, session)
39 local env = setmetatable({ print = session.print }, { __index = function (t, k) return rawget(_G, k); end });
40 env.dofile = function(name)
41 local f, err = envloadfile(name, env);
42 if not f then return f, err; end
50 function console:new_session(conn)
51 local w = function(s) conn:write(s:gsub("\n", "\r\n")); end;
52 local session = { conn = conn;
53 send = function (t) w(tostring(t)); end;
54 print = function (...)
56 for i=1,select("#", ...) do
57 t[i] = tostring(select(i, ...));
59 w("| "..table.concat(t, "\t").."\n");
61 disconnect = function () conn:close(); end;
63 session.env = setmetatable({}, default_env_mt);
65 -- Load up environment with helper objects
66 for name, t in pairs(def_env) do
67 if type(t) == "table" then
68 session.env[name] = setmetatable({ session = session }, { __index = t });
75 function console:process_line(session, line)
78 if line:match("^>") then
79 line = line:gsub("^>", "");
81 elseif line == "\004" then
82 commands["bye"](session, line);
85 local command = line:match("^%w+") or line:match("%p");
86 if commands[command] then
87 commands[command](session, line);
94 local chunkname = "=console";
95 local env = (useglobalenv and redirect_output(_G, session)) or session.env or nil
96 local chunk, err = envload("return "..line, chunkname, env);
98 chunk, err = envload(line, chunkname, env);
100 err = err:gsub("^%[string .-%]:%d+: ", "");
101 err = err:gsub("^:%d+: ", "");
102 err = err:gsub("'<eof>'", "the end of the line");
103 session.print("Sorry, I couldn't understand that... "..err);
108 local ranok, taskok, message = pcall(chunk);
110 if not (ranok or message or useglobalenv) and commands[line:lower()] then
111 commands[line:lower()](session, line);
116 session.print("Fatal error while running command, it did not complete");
117 session.print("Error: "..taskok);
122 session.print("Result: "..tostring(taskok));
124 elseif (not taskok) and message then
125 session.print("Command completed with a problem");
126 session.print("Message: "..tostring(message));
130 session.print("OK: "..tostring(message));
135 function console_listener.onconnect(conn)
136 -- Handle new connection
137 local session = console:new_session(conn);
138 sessions[conn] = session;
139 printbanner(session);
140 session.send(string.char(0));
143 function console_listener.onincoming(conn, data)
144 local session = sessions[conn];
146 local partial = session.partial_data;
148 data = partial..data;
151 for line in data:gmatch("[^\n]*[\n\004]") do
152 if session.closed then return end
153 console:process_line(session, line);
154 session.send(string.char(0));
156 session.partial_data = data:match("[^\n]+$");
159 function console_listener.ondisconnect(conn, err)
160 local session = sessions[conn];
162 session.disconnect();
163 sessions[conn] = nil;
167 -- Console commands --
168 -- These are simple commands, not valid standalone in Lua
170 function commands.bye(session)
171 session.print("See you! :)");
172 session.closed = true;
173 session.disconnect();
175 commands.quit, commands.exit = commands.bye, commands.bye;
177 commands["!"] = function (session, data)
178 if data:match("^!!") and session.env._ then
179 session.print("!> "..session.env._);
180 return console_listener.onincoming(session.conn, session.env._);
182 local old, new = data:match("^!(.-[^\\])!(.-)!$");
184 local ok, res = pcall(string.gsub, session.env._, old, new);
189 session.print("!> "..res);
190 return console_listener.onincoming(session.conn, res);
192 session.print("Sorry, not sure what you want");
196 function commands.help(session, data)
197 local print = session.print;
198 local section = data:match("^help (%w+)");
200 print [[Commands are divided into multiple sections. For help on a particular section, ]]
201 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
203 print [[c2s - Commands to manage local client-to-server sessions]]
204 print [[s2s - Commands to manage sessions between this server and others]]
205 print [[module - Commands to load/reload/unload modules/plugins]]
206 print [[host - Commands to activate, deactivate and list virtual hosts]]
207 print [[user - Commands to create and delete users, and change their passwords]]
208 print [[server - Uptime, version, shutting down, etc.]]
209 print [[port - Commands to manage ports the server is listening on]]
210 print [[dns - Commands to manage and inspect the internal DNS resolver]]
211 print [[config - Reloading the configuration, etc.]]
212 print [[console - Help regarding the console itself]]
213 elseif section == "c2s" then
214 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
215 print [[c2s:show_insecure() - Show all unencrypted client connections]]
216 print [[c2s:show_secure() - Show all encrypted client connections]]
217 print [[c2s:close(jid) - Close all sessions for the specified JID]]
218 elseif section == "s2s" then
219 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
220 print [[s2s:close(from, to) - Close a connection from one domain to another]]
221 print [[s2s:closeall(host) - Close all the incoming/outgoing s2s sessions to specified host]]
222 elseif section == "module" then
223 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
224 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
225 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
226 print [[module:list(host) - List the modules loaded on the specified host]]
227 elseif section == "host" then
228 print [[host:activate(hostname) - Activates the specified host]]
229 print [[host:deactivate(hostname) - Disconnects all clients on this host and deactivates]]
230 print [[host:list() - List the currently-activated hosts]]
231 elseif section == "user" then
232 print [[user:create(jid, password) - Create the specified user account]]
233 print [[user:password(jid, password) - Set the password for the specified user account]]
234 print [[user:delete(jid) - Permanently remove the specified user account]]
235 print [[user:list(hostname, pattern) - List users on the specified host, optionally filtering with a pattern]]
236 elseif section == "server" then
237 print [[server:version() - Show the server's version number]]
238 print [[server:uptime() - Show how long the server has been running]]
239 print [[server:memory() - Show details about the server's memory usage]]
240 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
241 elseif section == "port" then
242 print [[port:list() - Lists all network ports prosody currently listens on]]
243 print [[port:close(port, interface) - Close a port]]
244 elseif section == "dns" then
245 print [[dns:lookup(name, type, class) - Do a DNS lookup]]
246 print [[dns:addnameserver(nameserver) - Add a nameserver to the list]]
247 print [[dns:setnameserver(nameserver) - Replace the list of name servers with the supplied one]]
248 print [[dns:purge() - Clear the DNS cache]]
249 print [[dns:cache() - Show cached records]]
250 elseif section == "config" then
251 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
252 elseif section == "console" then
253 print [[Hey! Welcome to Prosody's admin console.]]
254 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
255 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
256 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
258 print [[For now we offer a couple of handy shortcuts:]]
259 print [[!! - Repeat the last command]]
260 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
262 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
263 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
264 print [[the running server. Great fun, but be careful not to break anything :)]]
269 -- Session environment --
270 -- Anything in def_env will be accessible within the session as a global variable
274 function def_env.server:insane_reload()
275 prosody.unlock_globals();
277 prosody = _G.prosody;
278 return true, "Server reloaded";
281 function def_env.server:version()
282 return true, tostring(prosody.version or "unknown");
285 function def_env.server:uptime()
286 local t = os.time()-prosody.start_time;
287 local seconds = t%60;
288 t = (t - seconds)/60;
289 local minutes = t%60;
290 t = (t - minutes)/60;
294 return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
295 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
296 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
299 function def_env.server:shutdown(reason)
300 prosody.shutdown(reason);
301 return true, "Shutdown initiated";
304 local function human(kb)
307 kb, unit = kb/1024, "M";
309 return ("%0.2f%sB"):format(kb, unit);
312 function def_env.server:memory()
313 if not pposix.meminfo then
314 return true, "Lua is using "..collectgarbage("count");
316 local mem, lua_mem = pposix.meminfo(), collectgarbage("count");
317 local print = self.session.print;
318 print("Process: "..human((mem.allocated+mem.allocated_mmap)/1024));
319 print(" Used: "..human(mem.used/1024).." ("..human(lua_mem).." by Lua)");
320 print(" Free: "..human(mem.unused/1024).." ("..human(mem.returnable/1024).." returnable)");
326 local function get_hosts_set(hosts, module)
327 if type(hosts) == "table" then
329 return set.new(hosts);
330 elseif hosts._items then
333 elseif type(hosts) == "string" then
334 return set.new { hosts };
335 elseif hosts == nil then
336 local mm = require "modulemanager";
337 local hosts_set = set.new(array.collect(keys(prosody.hosts)))
338 / function (host) return (prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module)) and host or nil; end;
339 if module and mm.get_module("*", module) then
346 function def_env.module:load(name, hosts, config)
347 local mm = require "modulemanager";
349 hosts = get_hosts_set(hosts);
351 -- Load the module for each host
352 local ok, err, count, mod = true, nil, 0, nil;
354 if (not mm.is_loaded(host, name)) then
355 mod, err = mm.load(host, name, config);
358 if err == "global-module-already-loaded" then
360 ok, err, count = true, nil, 1;
364 self.session.print(err or "Unknown error loading module");
367 self.session.print("Loaded for "..mod.module.host);
372 return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
375 function def_env.module:unload(name, hosts)
376 local mm = require "modulemanager";
378 hosts = get_hosts_set(hosts, name);
380 -- Unload the module for each host
381 local ok, err, count = true, nil, 0;
383 if mm.is_loaded(host, name) then
384 ok, err = mm.unload(host, name);
387 self.session.print(err or "Unknown error unloading module");
390 self.session.print("Unloaded from "..host);
394 return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
397 function def_env.module:reload(name, hosts)
398 local mm = require "modulemanager";
400 hosts = array.collect(get_hosts_set(hosts, name)):sort(function (a, b)
401 if a == "*" then return true
402 elseif b == "*" then return false
403 else return a < b; end
406 -- Reload the module for each host
407 local ok, err, count = true, nil, 0;
408 for _, host in ipairs(hosts) do
409 if mm.is_loaded(host, name) then
410 ok, err = mm.reload(host, name);
413 self.session.print(err or "Unknown error reloading module");
419 self.session.print("Reloaded on "..host);
423 return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
426 function def_env.module:list(hosts)
428 hosts = array.collect(keys(prosody.hosts));
429 table.insert(hosts, 1, "*");
431 if type(hosts) == "string" then
434 if type(hosts) ~= "table" then
435 return false, "Please supply a host or a list of hosts you would like to see";
438 local print = self.session.print;
439 for _, host in ipairs(hosts) do
440 print((host == "*" and "Global" or host)..":");
441 local modules = array.collect(keys(modulemanager.get_modules(host) or {})):sort();
442 if #modules == 0 then
443 if prosody.hosts[host] then
444 print(" No modules loaded");
446 print(" Host not found");
449 for _, name in ipairs(modules) do
457 function def_env.config:load(filename, format)
458 local config_load = require "core.configmanager".load;
459 local ok, err = config_load(filename, format);
461 return false, err or "Unknown error loading config";
463 return true, "Config loaded";
466 function def_env.config:get(host, section, key)
467 local config_get = require "core.configmanager".get
468 return true, tostring(config_get(host, section, key));
471 function def_env.config:reload()
472 local ok, err = prosody.reload_config();
473 return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
477 function def_env.hosts:list()
478 for host, host_session in pairs(hosts) do
479 self.session.print(host);
484 function def_env.hosts:add(name)
487 local function session_flags(session, line)
489 if session.cert_identity_status == "valid" then
490 line[#line+1] = "(secure)";
491 elseif session.secure then
492 line[#line+1] = "(encrypted)";
494 if session.compressed then
495 line[#line+1] = "(compressed)";
497 if session.smacks then
498 line[#line+1] = "(sm)";
500 if (session.ip or session.conn and session.conn:ip()):match(":") then
501 line[#line+1] = "(IPv6)";
503 return table.concat(line, " ");
508 local function show_c2s(callback)
509 for hostname, host in pairs(hosts) do
510 for username, user in pairs(host.sessions or {}) do
511 for resource, session in pairs(user.sessions or {}) do
512 local jid = username.."@"..hostname.."/"..resource;
513 callback(jid, session);
519 function def_env.c2s:count(match_jid)
521 show_c2s(function (jid, session)
522 if (not match_jid) or jid:match(match_jid) then
526 return true, "Total: "..count.." clients";
529 function def_env.c2s:show(match_jid)
530 local print, count = self.session.print, 0;
532 show_c2s(function (jid, session)
533 if curr_host ~= session.host then
534 curr_host = session.host;
537 if (not match_jid) or jid:match(match_jid) then
539 local status, priority = "unavailable", tostring(session.priority or "-");
540 if session.presence then
541 status = session.presence:child_with_name("show");
543 status = status:get_text() or "[invalid!]";
545 status = "available";
548 print(session_flags(session, { " "..jid.." - "..status.."("..priority..")" }));
551 return true, "Total: "..count.." clients";
554 function def_env.c2s:show_insecure(match_jid)
555 local print, count = self.session.print, 0;
556 show_c2s(function (jid, session)
557 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
562 return true, "Total: "..count.." insecure client connections";
565 function def_env.c2s:show_secure(match_jid)
566 local print, count = self.session.print, 0;
567 show_c2s(function (jid, session)
568 if ((not match_jid) or jid:match(match_jid)) and session.secure then
573 return true, "Total: "..count.." secure client connections";
576 function def_env.c2s:close(match_jid)
578 show_c2s(function (jid, session)
579 if jid == match_jid or jid_bare(jid) == match_jid then
584 return true, "Total: "..count.." sessions closed";
589 function def_env.s2s:show(match_jid)
590 local _print = self.session.print;
591 local print = self.session.print;
593 local count_in, count_out = 0,0;
595 for host, host_session in pairs(hosts) do
596 print = function (...) _print(host); _print(...); print = _print; end
597 for remotehost, session in pairs(host_session.s2sout) do
598 if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
599 count_out = count_out + 1;
600 print(session_flags(session, {" ", host, "->", remotehost}));
601 if session.sendq then
602 print(" There are "..#session.sendq.." queued outgoing stanzas for this connection");
604 if session.type == "s2sout_unauthed" then
605 if session.connecting then
606 print(" Connection not yet established");
607 if not session.srv_hosts then
608 if not session.conn then
609 print(" We do not yet have a DNS answer for this host's SRV records");
611 print(" This host has no SRV records, using A record instead");
613 elseif session.srv_choice then
614 print(" We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
615 local srv_choice = session.srv_hosts[session.srv_choice];
616 print(" Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
618 elseif session.notopen then
619 print(" The <stream> has not yet been opened");
620 elseif not session.dialback_key then
621 print(" Dialback has not been initiated yet");
622 elseif session.dialback_key then
623 print(" Dialback has been requested, but no result received");
628 local subhost_filter = function (h)
629 return (match_jid and h:match(match_jid));
631 for session in pairs(incoming_s2s) do
632 if session.to_host == host and ((not match_jid) or host:match(match_jid)
633 or (session.from_host and session.from_host:match(match_jid))
634 -- Pft! is what I say to list comprehensions
635 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
636 count_in = count_in + 1;
637 print(session_flags(session, {" ", host, "<-", session.from_host or "(unknown)"}));
638 if session.type == "s2sin_unauthed" then
639 print(" Connection not yet authenticated");
641 for name in pairs(session.hosts) do
642 if name ~= session.from_host then
643 print(" also hosts "..tostring(name));
652 for session in pairs(incoming_s2s) do
653 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
654 count_in = count_in + 1;
655 print("Other incoming s2s connections");
656 print(" (unknown) <- "..(session.from_host or "(unknown)"));
660 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
663 local function print_subject(print, subject)
664 for _, entry in ipairs(subject) do
667 entry.name or entry.oid,
668 entry.value:gsub("[\r\n%z%c]", " ")
674 -- As much as it pains me to use the 0-based depths that OpenSSL does,
675 -- I think there's going to be more confusion among operators if we
677 local function print_errors(print, errors)
678 for depth, t in ipairs(errors) do
682 table.concat(t, "\n| ")
688 function def_env.s2s:showcert(domain)
689 local ser = require "util.serialization".serialize;
690 local print = self.session.print;
691 local domain_sessions = set.new(array.collect(keys(incoming_s2s)))
692 /function(session) return session.from_host == domain and session or nil; end;
693 for local_host in values(prosody.hosts) do
694 local s2sout = local_host.s2sout;
695 if s2sout and s2sout[domain] then
696 domain_sessions:add(s2sout[domain]);
700 for session in domain_sessions do
701 local conn = session.conn;
702 conn = conn and conn:socket();
703 if not conn.getpeerchain then
704 if conn.dohandshake then
705 error("This version of LuaSec does not support certificate viewing");
708 local certs = conn:getpeerchain();
709 local cert = certs[1];
711 local digest = cert:digest("sha1");
712 if not cert_set[digest] then
713 local chain_valid, chain_errors = conn:getpeerverification();
716 from = session.from_host,
717 to = session.to_host,
718 direction = session.direction
720 chain_valid = chain_valid;
721 chain_errors = chain_errors;
725 table.insert(cert_set[digest], {
726 from = session.from_host,
727 to = session.to_host,
728 direction = session.direction
734 local domain_certs = array.collect(values(cert_set));
735 -- Phew. We now have a array of unique certificates presented by domain.
736 local n_certs = #domain_certs;
739 return "No certificates found for "..domain;
742 local function _capitalize_and_colon(byte)
743 return string.upper(byte)..":";
745 local function pretty_fingerprint(hash)
746 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
749 for cert_info in values(domain_certs) do
750 local certs = cert_info.certs;
751 local cert = certs[1];
753 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
755 local n_streams = #cert_info;
756 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
757 for _, stream in ipairs(cert_info) do
758 if stream.direction == "incoming" then
759 print(" "..stream.to.." <- "..stream.from);
761 print(" "..stream.from.." -> "..stream.to);
765 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
766 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
768 print("Trusted certificate: Yes");
770 print("Trusted certificate: No");
771 print_errors(print, errors);
775 print_subject(print, cert:issuer());
777 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
779 print_subject(print, cert:subject());
782 return ("Showing "..n_certs.." certificate"
783 ..(n_certs==1 and "" or "s")
784 .." presented by "..domain..".");
787 function def_env.s2s:close(from, to)
788 local print, count = self.session.print, 0;
790 if not (from and to) then
791 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
792 elseif from == to then
793 return false, "Both from and to are the same... you can't do that :)";
796 if hosts[from] and not hosts[to] then
797 -- Is an outgoing connection
798 local session = hosts[from].s2sout[to];
800 print("No outgoing connection from "..from.." to "..to)
802 (session.close or s2smanager.destroy_session)(session);
804 print("Closed outgoing session from "..from.." to "..to);
806 elseif hosts[to] and not hosts[from] then
807 -- Is an incoming connection
808 for session in pairs(incoming_s2s) do
809 if session.to_host == to and session.from_host == from then
810 (session.close or s2smanager.destroy_session)(session);
816 print("No incoming connections from "..from.." to "..to);
818 print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
820 elseif hosts[to] and hosts[from] then
821 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
823 return false, "Neither of the hostnames you specified are being used on this server";
826 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
829 function def_env.s2s:closeall(host)
832 if not host or type(host) ~= "string" then return false, "wrong syntax: please use s2s:closeall('hostname.tld')"; end
834 for session in pairs(incoming_s2s) do
835 if session.to_host == host then
836 (session.close or s2smanager.destroy_session)(session);
840 for _, session in pairs(hosts[host].s2sout) do
841 (session.close or s2smanager.destroy_session)(session);
845 for session in pairs(incoming_s2s) do
846 if session.from_host == host then
847 (session.close or s2smanager.destroy_session)(session);
851 for _, h in pairs(hosts) do
852 if h.s2sout[host] then
853 (h.s2sout[host].close or s2smanager.destroy_session)(h.s2sout[host]);
859 if count == 0 then return false, "No sessions to close.";
860 else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
863 def_env.host = {}; def_env.hosts = def_env.host;
865 function def_env.host:activate(hostname, config)
866 return hostmanager.activate(hostname, config);
868 function def_env.host:deactivate(hostname, reason)
869 return hostmanager.deactivate(hostname, reason);
872 function def_env.host:list()
873 local print = self.session.print;
875 for host in values(array.collect(keys(prosody.hosts)):sort()) do
879 return true, i.." hosts";
884 function def_env.port:list()
885 local print = self.session.print;
886 local services = portmanager.get_active_services().data;
887 local ordered_services, n_ports = {}, 0;
888 for service, interfaces in pairs(services) do
889 table.insert(ordered_services, service);
891 table.sort(ordered_services);
892 for _, service in ipairs(ordered_services) do
893 local ports_list = {};
894 for interface, ports in pairs(services[service]) do
895 for port in pairs(ports) do
896 table.insert(ports_list, "["..interface.."]:"..port);
899 n_ports = n_ports + #ports_list;
900 print(service..": "..table.concat(ports_list, ", "));
902 return true, #ordered_services.." services listening on "..n_ports.." ports";
905 function def_env.port:close(close_port, close_interface)
906 close_port = assert(tonumber(close_port), "Invalid port number");
908 local services = portmanager.get_active_services().data;
909 for service, interfaces in pairs(services) do
910 for interface, ports in pairs(interfaces) do
911 if not close_interface or close_interface == interface then
912 if ports[close_port] then
913 self.session.print("Closing ["..interface.."]:"..close_port.."...");
914 local ok, err = portmanager.close(interface, close_port)
916 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
918 n_closed = n_closed + 1;
924 return true, "Closed "..n_closed.." ports";
929 local console_room_mt = {
930 __index = function (self, k) return self.room[k]; end;
931 __tostring = function (self)
932 return "MUC room <"..self.room.jid..">";
936 local function check_muc(jid)
937 local room_name, host = jid_split(jid);
938 if not hosts[host] then
939 return nil, "No such host: "..host;
940 elseif not hosts[host].modules.muc then
941 return nil, "Host '"..host.."' is not a MUC service";
943 return room_name, host;
946 function def_env.muc:create(room_jid)
947 local room, host = check_muc(room_jid);
948 return hosts[host].modules.muc.create_room(room_jid);
951 function def_env.muc:room(room_jid)
952 local room_name, host = check_muc(room_jid);
953 local room_obj = hosts[host].modules.muc.rooms[room_jid];
955 return nil, "No such room: "..room_jid;
957 return setmetatable({ room = room_obj }, console_room_mt);
960 local um = require"core.usermanager";
963 function def_env.user:create(jid, password)
964 local username, host = jid_split(jid);
965 if um.user_exists(username, host) then
966 return nil, "User exists";
968 local ok, err = um.create_user(username, password, host);
970 return true, "User created";
972 return nil, "Could not create user: "..err;
976 function def_env.user:delete(jid)
977 local username, host = jid_split(jid);
978 if not um.user_exists(username, host) then
979 return nil, "No such user";
981 local ok, err = um.delete_user(username, host);
983 return true, "User deleted";
985 return nil, "Could not delete user: "..err;
989 function def_env.user:password(jid, password)
990 local username, host = jid_split(jid);
991 if not um.user_exists(username, host) then
992 return nil, "No such user";
994 local ok, err = um.set_password(username, password, host);
996 return true, "User password changed";
998 return nil, "Could not change password for user: "..err;
1002 function def_env.user:list(host, pat)
1004 return nil, "No host given";
1005 elseif not hosts[host] then
1006 return nil, "No such host";
1008 local print = self.session.print;
1009 local total, matches = 0, 0;
1010 for user in um.users(host) do
1011 if not pat or user:match(pat) then
1012 print(user.."@"..host);
1013 matches = matches + 1;
1017 return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
1022 local st = require "util.stanza";
1023 function def_env.xmpp:ping(localhost, remotehost)
1024 if hosts[localhost] then
1025 core_post_stanza(hosts[localhost],
1026 st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
1027 :tag("ping", {xmlns="urn:xmpp:ping"}));
1028 return true, "Sent ping";
1030 return nil, "No such host";
1035 local adns = require"net.adns";
1036 local dns = require"net.dns";
1038 function def_env.dns:lookup(name, typ, class)
1039 local ret = "Query sent";
1040 local print = self.session.print;
1041 local function handler(...)
1042 ret = "Got response";
1045 adns.lookup(handler, name, typ, class);
1049 function def_env.dns:addnameserver(...)
1050 dns.addnameserver(...)
1054 function def_env.dns:setnameserver(...)
1055 dns.setnameserver(...)
1059 function def_env.dns:purge()
1064 function def_env.dns:cache()
1065 return true, "Cache:\n"..tostring(dns.cache())
1070 function printbanner(session)
1071 local option = module:get_option("console_banner");
1072 if option == nil or option == "full" or option == "graphic" then
1075 | _ \ _ __ ___ ___ _-_ __| |_ _
1076 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1077 | __/| | | (_) \__ \ |_| | (_| | |_| |
1078 |_| |_| \___/|___/\___/ \__,_|\__, |
1079 A study in simplicity |___/
1083 if option == nil or option == "short" or option == "full" then
1084 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1085 session.print("You may find more help on using this console in our online documentation at ");
1086 session.print("http://prosody.im/doc/console\n");
1088 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
1089 if type(option) == "string" then
1090 session.print(option)
1091 elseif type(option) == "function" then
1092 module:log("warn", "Using functions as value for the console_banner option is no longer supported");
1097 module:provides("net", {
1099 listener = console_listener;
1100 default_port = 5582;