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)
489 local function show_c2s(callback)
490 for hostname, host in pairs(hosts) do
491 for username, user in pairs(host.sessions or {}) do
492 for resource, session in pairs(user.sessions or {}) do
493 local jid = username.."@"..hostname.."/"..resource;
494 callback(jid, session);
500 function def_env.c2s:count(match_jid)
502 show_c2s(function (jid, session)
503 if (not match_jid) or jid:match(match_jid) then
507 return true, "Total: "..count.." clients";
510 function def_env.c2s:show(match_jid)
511 local print, count = self.session.print, 0;
513 show_c2s(function (jid, session)
514 if curr_host ~= session.host then
515 curr_host = session.host;
518 if (not match_jid) or jid:match(match_jid) then
520 local status, priority = "unavailable", tostring(session.priority or "-");
521 if session.presence then
522 status = session.presence:child_with_name("show");
524 status = status:get_text() or "[invalid!]";
526 status = "available";
529 print(" "..jid.." - "..status.."("..priority..")");
532 return true, "Total: "..count.." clients";
535 function def_env.c2s:show_insecure(match_jid)
536 local print, count = self.session.print, 0;
537 show_c2s(function (jid, session)
538 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
543 return true, "Total: "..count.." insecure client connections";
546 function def_env.c2s:show_secure(match_jid)
547 local print, count = self.session.print, 0;
548 show_c2s(function (jid, session)
549 if ((not match_jid) or jid:match(match_jid)) and session.secure then
554 return true, "Total: "..count.." secure client connections";
557 function def_env.c2s:close(match_jid)
559 show_c2s(function (jid, session)
560 if jid == match_jid or jid_bare(jid) == match_jid then
565 return true, "Total: "..count.." sessions closed";
568 local function session_flags(session, line)
569 if session.cert_identity_status == "valid" then
570 line[#line+1] = "(secure)";
571 elseif session.secure then
572 line[#line+1] = "(encrypted)";
574 if session.compressed then
575 line[#line+1] = "(compressed)";
577 if session.smacks then
578 line[#line+1] = "(sm)";
580 if session.conn and session.conn:ip():match(":") then
581 line[#line+1] = "(IPv6)";
583 return table.concat(line, " ");
587 function def_env.s2s:show(match_jid)
588 local _print = self.session.print;
589 local print = self.session.print;
591 local count_in, count_out = 0,0;
593 for host, host_session in pairs(hosts) do
594 print = function (...) _print(host); _print(...); print = _print; end
595 for remotehost, session in pairs(host_session.s2sout) do
596 if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
597 count_out = count_out + 1;
598 print(session_flags(session, {" ", host, "->", remotehost}));
599 if session.sendq then
600 print(" There are "..#session.sendq.." queued outgoing stanzas for this connection");
602 if session.type == "s2sout_unauthed" then
603 if session.connecting then
604 print(" Connection not yet established");
605 if not session.srv_hosts then
606 if not session.conn then
607 print(" We do not yet have a DNS answer for this host's SRV records");
609 print(" This host has no SRV records, using A record instead");
611 elseif session.srv_choice then
612 print(" We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
613 local srv_choice = session.srv_hosts[session.srv_choice];
614 print(" Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
616 elseif session.notopen then
617 print(" The <stream> has not yet been opened");
618 elseif not session.dialback_key then
619 print(" Dialback has not been initiated yet");
620 elseif session.dialback_key then
621 print(" Dialback has been requested, but no result received");
626 local subhost_filter = function (h)
627 return (match_jid and h:match(match_jid));
629 for session in pairs(incoming_s2s) do
630 if session.to_host == host and ((not match_jid) or host:match(match_jid)
631 or (session.from_host and session.from_host:match(match_jid))
632 -- Pft! is what I say to list comprehensions
633 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
634 count_in = count_in + 1;
635 print(session_flags(session, {" ", host, "<-", session.from_host or "(unknown)"}));
636 if session.type == "s2sin_unauthed" then
637 print(" Connection not yet authenticated");
639 for name in pairs(session.hosts) do
640 if name ~= session.from_host then
641 print(" also hosts "..tostring(name));
650 for session in pairs(incoming_s2s) do
651 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
652 count_in = count_in + 1;
653 print("Other incoming s2s connections");
654 print(" (unknown) <- "..(session.from_host or "(unknown)"));
658 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
661 local function print_subject(print, subject)
662 for _, entry in ipairs(subject) do
665 entry.name or entry.oid,
666 entry.value:gsub("[\r\n%z%c]", " ")
672 -- As much as it pains me to use the 0-based depths that OpenSSL does,
673 -- I think there's going to be more confusion among operators if we
675 local function print_errors(print, errors)
676 for depth, t in ipairs(errors) do
680 table.concat(t, "\n| ")
686 function def_env.s2s:showcert(domain)
687 local ser = require "util.serialization".serialize;
688 local print = self.session.print;
689 local domain_sessions = set.new(array.collect(keys(incoming_s2s)))
690 /function(session) return session.from_host == domain and session or nil; end;
691 for local_host in values(prosody.hosts) do
692 local s2sout = local_host.s2sout;
693 if s2sout and s2sout[domain] then
694 domain_sessions:add(s2sout[domain]);
698 for session in domain_sessions do
699 local conn = session.conn;
700 conn = conn and conn:socket();
701 if not conn.getpeerchain then
702 if conn.dohandshake then
703 error("This version of LuaSec does not support certificate viewing");
706 local certs = conn:getpeerchain();
707 local cert = certs[1];
709 local digest = cert:digest("sha1");
710 if not cert_set[digest] then
711 local chain_valid, chain_errors = conn:getpeerverification();
714 from = session.from_host,
715 to = session.to_host,
716 direction = session.direction
718 chain_valid = chain_valid;
719 chain_errors = chain_errors;
723 table.insert(cert_set[digest], {
724 from = session.from_host,
725 to = session.to_host,
726 direction = session.direction
732 local domain_certs = array.collect(values(cert_set));
733 -- Phew. We now have a array of unique certificates presented by domain.
734 local n_certs = #domain_certs;
737 return "No certificates found for "..domain;
740 local function _capitalize_and_colon(byte)
741 return string.upper(byte)..":";
743 local function pretty_fingerprint(hash)
744 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
747 for cert_info in values(domain_certs) do
748 local certs = cert_info.certs;
749 local cert = certs[1];
751 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
753 local n_streams = #cert_info;
754 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
755 for _, stream in ipairs(cert_info) do
756 if stream.direction == "incoming" then
757 print(" "..stream.to.." <- "..stream.from);
759 print(" "..stream.from.." -> "..stream.to);
763 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
764 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
766 print("Trusted certificate: Yes");
768 print("Trusted certificate: No");
769 print_errors(print, errors);
773 print_subject(print, cert:issuer());
775 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
777 print_subject(print, cert:subject());
780 return ("Showing "..n_certs.." certificate"
781 ..(n_certs==1 and "" or "s")
782 .." presented by "..domain..".");
785 function def_env.s2s:close(from, to)
786 local print, count = self.session.print, 0;
788 if not (from and to) then
789 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
790 elseif from == to then
791 return false, "Both from and to are the same... you can't do that :)";
794 if hosts[from] and not hosts[to] then
795 -- Is an outgoing connection
796 local session = hosts[from].s2sout[to];
798 print("No outgoing connection from "..from.." to "..to)
800 (session.close or s2smanager.destroy_session)(session);
802 print("Closed outgoing session from "..from.." to "..to);
804 elseif hosts[to] and not hosts[from] then
805 -- Is an incoming connection
806 for session in pairs(incoming_s2s) do
807 if session.to_host == to and session.from_host == from then
808 (session.close or s2smanager.destroy_session)(session);
814 print("No incoming connections from "..from.." to "..to);
816 print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
818 elseif hosts[to] and hosts[from] then
819 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
821 return false, "Neither of the hostnames you specified are being used on this server";
824 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
827 function def_env.s2s:closeall(host)
830 if not host or type(host) ~= "string" then return false, "wrong syntax: please use s2s:closeall('hostname.tld')"; end
832 for session in pairs(incoming_s2s) do
833 if session.to_host == host then
834 (session.close or s2smanager.destroy_session)(session);
838 for _, session in pairs(hosts[host].s2sout) do
839 (session.close or s2smanager.destroy_session)(session);
843 for session in pairs(incoming_s2s) do
844 if session.from_host == host then
845 (session.close or s2smanager.destroy_session)(session);
849 for _, h in pairs(hosts) do
850 if h.s2sout[host] then
851 (h.s2sout[host].close or s2smanager.destroy_session)(h.s2sout[host]);
857 if count == 0 then return false, "No sessions to close.";
858 else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
861 def_env.host = {}; def_env.hosts = def_env.host;
863 function def_env.host:activate(hostname, config)
864 return hostmanager.activate(hostname, config);
866 function def_env.host:deactivate(hostname, reason)
867 return hostmanager.deactivate(hostname, reason);
870 function def_env.host:list()
871 local print = self.session.print;
873 for host in values(array.collect(keys(prosody.hosts)):sort()) do
877 return true, i.." hosts";
882 function def_env.port:list()
883 local print = self.session.print;
884 local services = portmanager.get_active_services().data;
885 local ordered_services, n_ports = {}, 0;
886 for service, interfaces in pairs(services) do
887 table.insert(ordered_services, service);
889 table.sort(ordered_services);
890 for _, service in ipairs(ordered_services) do
891 local ports_list = {};
892 for interface, ports in pairs(services[service]) do
893 for port in pairs(ports) do
894 table.insert(ports_list, "["..interface.."]:"..port);
897 n_ports = n_ports + #ports_list;
898 print(service..": "..table.concat(ports_list, ", "));
900 return true, #ordered_services.." services listening on "..n_ports.." ports";
903 function def_env.port:close(close_port, close_interface)
904 close_port = assert(tonumber(close_port), "Invalid port number");
906 local services = portmanager.get_active_services().data;
907 for service, interfaces in pairs(services) do
908 for interface, ports in pairs(interfaces) do
909 if not close_interface or close_interface == interface then
910 if ports[close_port] then
911 self.session.print("Closing ["..interface.."]:"..close_port.."...");
912 local ok, err = portmanager.close(interface, close_port)
914 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
916 n_closed = n_closed + 1;
922 return true, "Closed "..n_closed.." ports";
927 local console_room_mt = {
928 __index = function (self, k) return self.room[k]; end;
929 __tostring = function (self)
930 return "MUC room <"..self.room.jid..">";
934 local function check_muc(jid)
935 local room_name, host = jid_split(jid);
936 if not hosts[host] then
937 return nil, "No such host: "..host;
938 elseif not hosts[host].modules.muc then
939 return nil, "Host '"..host.."' is not a MUC service";
941 return room_name, host;
944 function def_env.muc:create(room_jid)
945 local room, host = check_muc(room_jid);
946 return hosts[host].modules.muc.create_room(room_jid);
949 function def_env.muc:room(room_jid)
950 local room_name, host = check_muc(room_jid);
951 local room_obj = hosts[host].modules.muc.rooms[room_jid];
953 return nil, "No such room: "..room_jid;
955 return setmetatable({ room = room_obj }, console_room_mt);
958 local um = require"core.usermanager";
961 function def_env.user:create(jid, password)
962 local username, host = jid_split(jid);
963 if um.user_exists(username, host) then
964 return nil, "User exists";
966 local ok, err = um.create_user(username, password, host);
968 return true, "User created";
970 return nil, "Could not create user: "..err;
974 function def_env.user:delete(jid)
975 local username, host = jid_split(jid);
976 if not um.user_exists(username, host) then
977 return nil, "No such user";
979 local ok, err = um.delete_user(username, host);
981 return true, "User deleted";
983 return nil, "Could not delete user: "..err;
987 function def_env.user:password(jid, password)
988 local username, host = jid_split(jid);
989 if not um.user_exists(username, host) then
990 return nil, "No such user";
992 local ok, err = um.set_password(username, password, host);
994 return true, "User password changed";
996 return nil, "Could not change password for user: "..err;
1000 function def_env.user:list(host, pat)
1002 return nil, "No host given";
1003 elseif not hosts[host] then
1004 return nil, "No such host";
1006 local print = self.session.print;
1007 local total, matches = 0, 0;
1008 for user in um.users(host) do
1009 if not pat or user:match(pat) then
1010 print(user.."@"..host);
1011 matches = matches + 1;
1015 return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
1020 local st = require "util.stanza";
1021 function def_env.xmpp:ping(localhost, remotehost)
1022 if hosts[localhost] then
1023 core_post_stanza(hosts[localhost],
1024 st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
1025 :tag("ping", {xmlns="urn:xmpp:ping"}));
1026 return true, "Sent ping";
1028 return nil, "No such host";
1033 local adns = require"net.adns";
1034 local dns = require"net.dns";
1036 function def_env.dns:lookup(name, typ, class)
1037 local ret = "Query sent";
1038 local print = self.session.print;
1039 local function handler(...)
1040 ret = "Got response";
1043 adns.lookup(handler, name, typ, class);
1047 function def_env.dns:addnameserver(...)
1048 dns.addnameserver(...)
1052 function def_env.dns:setnameserver(...)
1053 dns.setnameserver(...)
1057 function def_env.dns:purge()
1062 function def_env.dns:cache()
1063 return true, "Cache:\n"..tostring(dns.cache())
1068 function printbanner(session)
1069 local option = module:get_option("console_banner");
1070 if option == nil or option == "full" or option == "graphic" then
1073 | _ \ _ __ ___ ___ _-_ __| |_ _
1074 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1075 | __/| | | (_) \__ \ |_| | (_| | |_| |
1076 |_| |_| \___/|___/\___/ \__,_|\__, |
1077 A study in simplicity |___/
1081 if option == nil or option == "short" or option == "full" then
1082 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1083 session.print("You may find more help on using this console in our online documentation at ");
1084 session.print("http://prosody.im/doc/console\n");
1086 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
1087 if type(option) == "string" then
1088 session.print(option)
1089 elseif type(option) == "function" then
1090 module:log("warn", "Using functions as value for the console_banner option is no longer supported");
1095 module:provides("net", {
1097 listener = console_listener;
1098 default_port = 5582;