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:get_child_text("show") or "available";
543 print(session_flags(session, { " "..jid.." - "..status.."("..priority..")" }));
546 return true, "Total: "..count.." clients";
549 function def_env.c2s:show_insecure(match_jid)
550 local print, count = self.session.print, 0;
551 show_c2s(function (jid, session)
552 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
557 return true, "Total: "..count.." insecure client connections";
560 function def_env.c2s:show_secure(match_jid)
561 local print, count = self.session.print, 0;
562 show_c2s(function (jid, session)
563 if ((not match_jid) or jid:match(match_jid)) and session.secure then
568 return true, "Total: "..count.." secure client connections";
571 function def_env.c2s:close(match_jid)
573 show_c2s(function (jid, session)
574 if jid == match_jid or jid_bare(jid) == match_jid then
579 return true, "Total: "..count.." sessions closed";
584 function def_env.s2s:show(match_jid)
585 local _print = self.session.print;
586 local print = self.session.print;
588 local count_in, count_out = 0,0;
590 for host, host_session in pairs(hosts) do
591 print = function (...) _print(host); _print(...); print = _print; end
592 for remotehost, session in pairs(host_session.s2sout) do
593 if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
594 count_out = count_out + 1;
595 print(session_flags(session, {" ", host, "->", remotehost}));
596 if session.sendq then
597 print(" There are "..#session.sendq.." queued outgoing stanzas for this connection");
599 if session.type == "s2sout_unauthed" then
600 if session.connecting then
601 print(" Connection not yet established");
602 if not session.srv_hosts then
603 if not session.conn then
604 print(" We do not yet have a DNS answer for this host's SRV records");
606 print(" This host has no SRV records, using A record instead");
608 elseif session.srv_choice then
609 print(" We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
610 local srv_choice = session.srv_hosts[session.srv_choice];
611 print(" Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
613 elseif session.notopen then
614 print(" The <stream> has not yet been opened");
615 elseif not session.dialback_key then
616 print(" Dialback has not been initiated yet");
617 elseif session.dialback_key then
618 print(" Dialback has been requested, but no result received");
623 local subhost_filter = function (h)
624 return (match_jid and h:match(match_jid));
626 for session in pairs(incoming_s2s) do
627 if session.to_host == host and ((not match_jid) or host:match(match_jid)
628 or (session.from_host and session.from_host:match(match_jid))
629 -- Pft! is what I say to list comprehensions
630 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
631 count_in = count_in + 1;
632 print(session_flags(session, {" ", host, "<-", session.from_host or "(unknown)"}));
633 if session.type == "s2sin_unauthed" then
634 print(" Connection not yet authenticated");
636 for name in pairs(session.hosts) do
637 if name ~= session.from_host then
638 print(" also hosts "..tostring(name));
647 for session in pairs(incoming_s2s) do
648 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
649 count_in = count_in + 1;
650 print("Other incoming s2s connections");
651 print(" (unknown) <- "..(session.from_host or "(unknown)"));
655 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
658 local function print_subject(print, subject)
659 for _, entry in ipairs(subject) do
662 entry.name or entry.oid,
663 entry.value:gsub("[\r\n%z%c]", " ")
669 -- As much as it pains me to use the 0-based depths that OpenSSL does,
670 -- I think there's going to be more confusion among operators if we
672 local function print_errors(print, errors)
673 for depth, t in ipairs(errors) do
677 table.concat(t, "\n| ")
683 function def_env.s2s:showcert(domain)
684 local ser = require "util.serialization".serialize;
685 local print = self.session.print;
686 local domain_sessions = set.new(array.collect(keys(incoming_s2s)))
687 /function(session) return session.from_host == domain and session or nil; end;
688 for local_host in values(prosody.hosts) do
689 local s2sout = local_host.s2sout;
690 if s2sout and s2sout[domain] then
691 domain_sessions:add(s2sout[domain]);
695 for session in domain_sessions do
696 local conn = session.conn;
697 conn = conn and conn:socket();
698 if not conn.getpeerchain then
699 if conn.dohandshake then
700 error("This version of LuaSec does not support certificate viewing");
703 local cert = conn:getpeercertificate();
705 local certs = conn:getpeerchain();
706 local digest = cert:digest("sha1");
707 if not cert_set[digest] then
708 local chain_valid, chain_errors = conn:getpeerverification();
711 from = session.from_host,
712 to = session.to_host,
713 direction = session.direction
715 chain_valid = chain_valid;
716 chain_errors = chain_errors;
720 table.insert(cert_set[digest], {
721 from = session.from_host,
722 to = session.to_host,
723 direction = session.direction
729 local domain_certs = array.collect(values(cert_set));
730 -- Phew. We now have a array of unique certificates presented by domain.
731 local n_certs = #domain_certs;
734 return "No certificates found for "..domain;
737 local function _capitalize_and_colon(byte)
738 return string.upper(byte)..":";
740 local function pretty_fingerprint(hash)
741 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
744 for cert_info in values(domain_certs) do
745 local certs = cert_info.certs;
746 local cert = certs[1];
748 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
750 local n_streams = #cert_info;
751 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
752 for _, stream in ipairs(cert_info) do
753 if stream.direction == "incoming" then
754 print(" "..stream.to.." <- "..stream.from);
756 print(" "..stream.from.." -> "..stream.to);
760 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
761 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
763 print("Trusted certificate: Yes");
765 print("Trusted certificate: No");
766 print_errors(print, errors);
770 print_subject(print, cert:issuer());
772 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
774 print_subject(print, cert:subject());
777 return ("Showing "..n_certs.." certificate"
778 ..(n_certs==1 and "" or "s")
779 .." presented by "..domain..".");
782 function def_env.s2s:close(from, to)
783 local print, count = self.session.print, 0;
785 if not (from and to) then
786 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
787 elseif from == to then
788 return false, "Both from and to are the same... you can't do that :)";
791 if hosts[from] and not hosts[to] then
792 -- Is an outgoing connection
793 local session = hosts[from].s2sout[to];
795 print("No outgoing connection from "..from.." to "..to)
797 (session.close or s2smanager.destroy_session)(session);
799 print("Closed outgoing session from "..from.." to "..to);
801 elseif hosts[to] and not hosts[from] then
802 -- Is an incoming connection
803 for session in pairs(incoming_s2s) do
804 if session.to_host == to and session.from_host == from then
805 (session.close or s2smanager.destroy_session)(session);
811 print("No incoming connections from "..from.." to "..to);
813 print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
815 elseif hosts[to] and hosts[from] then
816 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
818 return false, "Neither of the hostnames you specified are being used on this server";
821 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
824 function def_env.s2s:closeall(host)
827 if not host or type(host) ~= "string" then return false, "wrong syntax: please use s2s:closeall('hostname.tld')"; end
829 for session in pairs(incoming_s2s) do
830 if session.to_host == host then
831 (session.close or s2smanager.destroy_session)(session);
835 for _, session in pairs(hosts[host].s2sout) do
836 (session.close or s2smanager.destroy_session)(session);
840 for session in pairs(incoming_s2s) do
841 if session.from_host == host then
842 (session.close or s2smanager.destroy_session)(session);
846 for _, h in pairs(hosts) do
847 if h.s2sout[host] then
848 (h.s2sout[host].close or s2smanager.destroy_session)(h.s2sout[host]);
854 if count == 0 then return false, "No sessions to close.";
855 else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
858 def_env.host = {}; def_env.hosts = def_env.host;
860 function def_env.host:activate(hostname, config)
861 return hostmanager.activate(hostname, config);
863 function def_env.host:deactivate(hostname, reason)
864 return hostmanager.deactivate(hostname, reason);
867 function def_env.host:list()
868 local print = self.session.print;
870 for host in values(array.collect(keys(prosody.hosts)):sort()) do
874 return true, i.." hosts";
879 function def_env.port:list()
880 local print = self.session.print;
881 local services = portmanager.get_active_services().data;
882 local ordered_services, n_ports = {}, 0;
883 for service, interfaces in pairs(services) do
884 table.insert(ordered_services, service);
886 table.sort(ordered_services);
887 for _, service in ipairs(ordered_services) do
888 local ports_list = {};
889 for interface, ports in pairs(services[service]) do
890 for port in pairs(ports) do
891 table.insert(ports_list, "["..interface.."]:"..port);
894 n_ports = n_ports + #ports_list;
895 print(service..": "..table.concat(ports_list, ", "));
897 return true, #ordered_services.." services listening on "..n_ports.." ports";
900 function def_env.port:close(close_port, close_interface)
901 close_port = assert(tonumber(close_port), "Invalid port number");
903 local services = portmanager.get_active_services().data;
904 for service, interfaces in pairs(services) do
905 for interface, ports in pairs(interfaces) do
906 if not close_interface or close_interface == interface then
907 if ports[close_port] then
908 self.session.print("Closing ["..interface.."]:"..close_port.."...");
909 local ok, err = portmanager.close(interface, close_port)
911 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
913 n_closed = n_closed + 1;
919 return true, "Closed "..n_closed.." ports";
924 local console_room_mt = {
925 __index = function (self, k) return self.room[k]; end;
926 __tostring = function (self)
927 return "MUC room <"..self.room.jid..">";
931 local function check_muc(jid)
932 local room_name, host = jid_split(jid);
933 if not hosts[host] then
934 return nil, "No such host: "..host;
935 elseif not hosts[host].modules.muc then
936 return nil, "Host '"..host.."' is not a MUC service";
938 return room_name, host;
941 function def_env.muc:create(room_jid)
942 local room, host = check_muc(room_jid);
943 return hosts[host].modules.muc.create_room(room_jid);
946 function def_env.muc:room(room_jid)
947 local room_name, host = check_muc(room_jid);
948 local room_obj = hosts[host].modules.muc.rooms[room_jid];
950 return nil, "No such room: "..room_jid;
952 return setmetatable({ room = room_obj }, console_room_mt);
955 local um = require"core.usermanager";
958 function def_env.user:create(jid, password)
959 local username, host = jid_split(jid);
960 if not hosts[host] then
961 return nil, "No such host: "..host;
962 elseif um.user_exists(username, host) then
963 return nil, "User exists";
965 local ok, err = um.create_user(username, password, host);
967 return true, "User created";
969 return nil, "Could not create user: "..err;
973 function def_env.user:delete(jid)
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, "No such user";
980 local ok, err = um.delete_user(username, host);
982 return true, "User deleted";
984 return nil, "Could not delete user: "..err;
988 function def_env.user:password(jid, password)
989 local username, host = jid_split(jid);
990 if not hosts[host] then
991 return nil, "No such host: "..host;
992 elseif um.user_exists(username, host) then
993 return nil, "No such user";
995 local ok, err = um.set_password(username, password, host);
997 return true, "User password changed";
999 return nil, "Could not change password for user: "..err;
1003 function def_env.user:list(host, pat)
1005 return nil, "No host given";
1006 elseif not hosts[host] then
1007 return nil, "No such host";
1009 local print = self.session.print;
1010 local total, matches = 0, 0;
1011 for user in um.users(host) do
1012 if not pat or user:match(pat) then
1013 print(user.."@"..host);
1014 matches = matches + 1;
1018 return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
1023 local st = require "util.stanza";
1024 function def_env.xmpp:ping(localhost, remotehost)
1025 if hosts[localhost] then
1026 core_post_stanza(hosts[localhost],
1027 st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
1028 :tag("ping", {xmlns="urn:xmpp:ping"}));
1029 return true, "Sent ping";
1031 return nil, "No such host";
1036 local adns = require"net.adns";
1037 local dns = require"net.dns";
1039 function def_env.dns:lookup(name, typ, class)
1040 local ret = "Query sent";
1041 local print = self.session.print;
1042 local function handler(...)
1043 ret = "Got response";
1046 adns.lookup(handler, name, typ, class);
1050 function def_env.dns:addnameserver(...)
1051 dns.addnameserver(...)
1055 function def_env.dns:setnameserver(...)
1056 dns.setnameserver(...)
1060 function def_env.dns:purge()
1065 function def_env.dns:cache()
1066 return true, "Cache:\n"..tostring(dns.cache())
1071 function printbanner(session)
1072 local option = module:get_option("console_banner");
1073 if option == nil or option == "full" or option == "graphic" then
1076 | _ \ _ __ ___ ___ _-_ __| |_ _
1077 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1078 | __/| | | (_) \__ \ |_| | (_| | |_| |
1079 |_| |_| \___/|___/\___/ \__,_|\__, |
1080 A study in simplicity |___/
1084 if option == nil or option == "short" or option == "full" then
1085 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1086 session.print("You may find more help on using this console in our online documentation at ");
1087 session.print("http://prosody.im/doc/console\n");
1089 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
1090 if type(option) == "string" then
1091 session.print(option)
1092 elseif type(option) == "function" then
1093 module:log("warn", "Using functions as value for the console_banner option is no longer supported");
1098 module:provides("net", {
1100 listener = console_listener;
1101 default_port = 5582;