2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
11 local hostmanager = require "core.hostmanager";
12 local modulemanager = require "core.modulemanager";
13 local s2smanager = require "core.s2smanager";
14 local portmanager = require "core.portmanager";
18 local prosody = _G.prosody;
19 local hosts = prosody.hosts;
20 local incoming_s2s = prosody.incoming_s2s;
22 local console_listener = { default_port = 5582; default_mode = "*a"; interface = "127.0.0.1" };
24 local iterators = require "util.iterators";
25 local keys, values = iterators.keys, iterators.values;
26 local jid_bare, jid_split = import("util.jid", "bare", "prepped_split");
27 local set, array = require "util.set", require "util.array";
28 local cert_verify_identity = require "util.x509".verify_identity;
29 local envload = require "util.envload".envload;
30 local envloadfile = require "util.envload".envloadfile;
32 local commands = module:shared("commands")
33 local def_env = module:shared("env");
34 local default_env_mt = { __index = def_env };
35 local core_post_stanza = prosody.core_post_stanza;
37 local function redirect_output(_G, session)
38 local env = setmetatable({ print = session.print }, { __index = function (t, k) return rawget(_G, k); end });
39 env.dofile = function(name)
40 local f, err = envloadfile(name, env);
41 if not f then return f, err; end
49 function console:new_session(conn)
50 local w = function(s) conn:write(s:gsub("\n", "\r\n")); end;
51 local session = { conn = conn;
52 send = function (t) w(tostring(t)); end;
53 print = function (...)
55 for i=1,select("#", ...) do
56 t[i] = tostring(select(i, ...));
58 w("| "..table.concat(t, "\t").."\n");
60 disconnect = function () conn:close(); end;
62 session.env = setmetatable({}, default_env_mt);
64 -- Load up environment with helper objects
65 for name, t in pairs(def_env) do
66 if type(t) == "table" then
67 session.env[name] = setmetatable({ session = session }, { __index = t });
74 function console:process_line(session, line)
77 if line:match("^>") then
78 line = line:gsub("^>", "");
80 elseif line == "\004" then
81 commands["bye"](session, line);
84 local command = line:match("^%w+") or line:match("%p");
85 if commands[command] then
86 commands[command](session, line);
93 local chunkname = "=console";
94 local env = (useglobalenv and redirect_output(_G, session)) or session.env or nil
95 local chunk, err = envload("return "..line, chunkname, env);
97 chunk, err = envload(line, chunkname, env);
99 err = err:gsub("^%[string .-%]:%d+: ", "");
100 err = err:gsub("^:%d+: ", "");
101 err = err:gsub("'<eof>'", "the end of the line");
102 session.print("Sorry, I couldn't understand that... "..err);
107 local ranok, taskok, message = pcall(chunk);
109 if not (ranok or message or useglobalenv) and commands[line:lower()] then
110 commands[line:lower()](session, line);
115 session.print("Fatal error while running command, it did not complete");
116 session.print("Error: "..taskok);
121 session.print("Result: "..tostring(taskok));
123 elseif (not taskok) and message then
124 session.print("Command completed with a problem");
125 session.print("Message: "..tostring(message));
129 session.print("OK: "..tostring(message));
134 function console_listener.onconnect(conn)
135 -- Handle new connection
136 local session = console:new_session(conn);
137 sessions[conn] = session;
138 printbanner(session);
139 session.send(string.char(0));
142 function console_listener.onincoming(conn, data)
143 local session = sessions[conn];
145 local partial = session.partial_data;
147 data = partial..data;
150 for line in data:gmatch("[^\n]*[\n\004]") do
151 if session.closed then return end
152 console:process_line(session, line);
153 session.send(string.char(0));
155 session.partial_data = data:match("[^\n]+$");
158 function console_listener.ondisconnect(conn, err)
159 local session = sessions[conn];
161 session.disconnect();
162 sessions[conn] = nil;
166 function console_listener.ondetach(conn)
167 sessions[conn] = nil;
170 -- Console commands --
171 -- These are simple commands, not valid standalone in Lua
173 function commands.bye(session)
174 session.print("See you! :)");
175 session.closed = true;
176 session.disconnect();
178 commands.quit, commands.exit = commands.bye, commands.bye;
180 commands["!"] = function (session, data)
181 if data:match("^!!") and session.env._ then
182 session.print("!> "..session.env._);
183 return console_listener.onincoming(session.conn, session.env._);
185 local old, new = data:match("^!(.-[^\\])!(.-)!$");
187 local ok, res = pcall(string.gsub, session.env._, old, new);
192 session.print("!> "..res);
193 return console_listener.onincoming(session.conn, res);
195 session.print("Sorry, not sure what you want");
199 function commands.help(session, data)
200 local print = session.print;
201 local section = data:match("^help (%w+)");
203 print [[Commands are divided into multiple sections. For help on a particular section, ]]
204 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
206 print [[c2s - Commands to manage local client-to-server sessions]]
207 print [[s2s - Commands to manage sessions between this server and others]]
208 print [[module - Commands to load/reload/unload modules/plugins]]
209 print [[host - Commands to activate, deactivate and list virtual hosts]]
210 print [[user - Commands to create and delete users, and change their passwords]]
211 print [[server - Uptime, version, shutting down, etc.]]
212 print [[port - Commands to manage ports the server is listening on]]
213 print [[dns - Commands to manage and inspect the internal DNS resolver]]
214 print [[config - Reloading the configuration, etc.]]
215 print [[console - Help regarding the console itself]]
216 elseif section == "c2s" then
217 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
218 print [[c2s:show_insecure() - Show all unencrypted client connections]]
219 print [[c2s:show_secure() - Show all encrypted client connections]]
220 print [[c2s:close(jid) - Close all sessions for the specified JID]]
221 elseif section == "s2s" then
222 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
223 print [[s2s:close(from, to) - Close a connection from one domain to another]]
224 print [[s2s:closeall(host) - Close all the incoming/outgoing s2s sessions to specified host]]
225 elseif section == "module" then
226 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
227 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
228 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
229 print [[module:list(host) - List the modules loaded on the specified host]]
230 elseif section == "host" then
231 print [[host:activate(hostname) - Activates the specified host]]
232 print [[host:deactivate(hostname) - Disconnects all clients on this host and deactivates]]
233 print [[host:list() - List the currently-activated hosts]]
234 elseif section == "user" then
235 print [[user:create(jid, password) - Create the specified user account]]
236 print [[user:password(jid, password) - Set the password for the specified user account]]
237 print [[user:delete(jid) - Permanently remove the specified user account]]
238 print [[user:list(hostname, pattern) - List users on the specified host, optionally filtering with a pattern]]
239 elseif section == "server" then
240 print [[server:version() - Show the server's version number]]
241 print [[server:uptime() - Show how long the server has been running]]
242 print [[server:memory() - Show details about the server's memory usage]]
243 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
244 elseif section == "port" then
245 print [[port:list() - Lists all network ports prosody currently listens on]]
246 print [[port:close(port, interface) - Close a port]]
247 elseif section == "dns" then
248 print [[dns:lookup(name, type, class) - Do a DNS lookup]]
249 print [[dns:addnameserver(nameserver) - Add a nameserver to the list]]
250 print [[dns:setnameserver(nameserver) - Replace the list of name servers with the supplied one]]
251 print [[dns:purge() - Clear the DNS cache]]
252 print [[dns:cache() - Show cached records]]
253 elseif section == "config" then
254 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
255 elseif section == "console" then
256 print [[Hey! Welcome to Prosody's admin console.]]
257 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
258 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
259 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
261 print [[For now we offer a couple of handy shortcuts:]]
262 print [[!! - Repeat the last command]]
263 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
265 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
266 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
267 print [[the running server. Great fun, but be careful not to break anything :)]]
272 -- Session environment --
273 -- Anything in def_env will be accessible within the session as a global variable
277 function def_env.server:insane_reload()
278 prosody.unlock_globals();
280 prosody = _G.prosody;
281 return true, "Server reloaded";
284 function def_env.server:version()
285 return true, tostring(prosody.version or "unknown");
288 function def_env.server:uptime()
289 local t = os.time()-prosody.start_time;
290 local seconds = t%60;
291 t = (t - seconds)/60;
292 local minutes = t%60;
293 t = (t - minutes)/60;
297 return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
298 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
299 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
302 function def_env.server:shutdown(reason)
303 prosody.shutdown(reason);
304 return true, "Shutdown initiated";
307 local function human(kb)
310 kb, unit = kb/1024, "M";
312 return ("%0.2f%sB"):format(kb, unit);
315 function def_env.server:memory()
316 if not pposix.meminfo then
317 return true, "Lua is using "..collectgarbage("count");
319 local mem, lua_mem = pposix.meminfo(), collectgarbage("count");
320 local print = self.session.print;
321 print("Process: "..human((mem.allocated+mem.allocated_mmap)/1024));
322 print(" Used: "..human(mem.used/1024).." ("..human(lua_mem).." by Lua)");
323 print(" Free: "..human(mem.unused/1024).." ("..human(mem.returnable/1024).." returnable)");
329 local function get_hosts_set(hosts, module)
330 if type(hosts) == "table" then
332 return set.new(hosts);
333 elseif hosts._items then
336 elseif type(hosts) == "string" then
337 return set.new { hosts };
338 elseif hosts == nil then
339 local mm = require "modulemanager";
340 local hosts_set = set.new(array.collect(keys(prosody.hosts)))
341 / function (host) return (prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module)) and host or nil; end;
342 if module and mm.get_module("*", module) then
349 function def_env.module:load(name, hosts, config)
350 local mm = require "modulemanager";
352 hosts = get_hosts_set(hosts);
354 -- Load the module for each host
355 local ok, err, count, mod = true, nil, 0, nil;
357 if (not mm.is_loaded(host, name)) then
358 mod, err = mm.load(host, name, config);
361 if err == "global-module-already-loaded" then
363 ok, err, count = true, nil, 1;
367 self.session.print(err or "Unknown error loading module");
370 self.session.print("Loaded for "..mod.module.host);
375 return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
378 function def_env.module:unload(name, hosts)
379 local mm = require "modulemanager";
381 hosts = get_hosts_set(hosts, name);
383 -- Unload the module for each host
384 local ok, err, count = true, nil, 0;
386 if mm.is_loaded(host, name) then
387 ok, err = mm.unload(host, name);
390 self.session.print(err or "Unknown error unloading module");
393 self.session.print("Unloaded from "..host);
397 return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
400 function def_env.module:reload(name, hosts)
401 local mm = require "modulemanager";
403 hosts = array.collect(get_hosts_set(hosts, name)):sort(function (a, b)
404 if a == "*" then return true
405 elseif b == "*" then return false
406 else return a < b; end
409 -- Reload the module for each host
410 local ok, err, count = true, nil, 0;
411 for _, host in ipairs(hosts) do
412 if mm.is_loaded(host, name) then
413 ok, err = mm.reload(host, name);
416 self.session.print(err or "Unknown error reloading module");
422 self.session.print("Reloaded on "..host);
426 return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
429 function def_env.module:list(hosts)
431 hosts = array.collect(keys(prosody.hosts));
432 table.insert(hosts, 1, "*");
434 if type(hosts) == "string" then
437 if type(hosts) ~= "table" then
438 return false, "Please supply a host or a list of hosts you would like to see";
441 local print = self.session.print;
442 for _, host in ipairs(hosts) do
443 print((host == "*" and "Global" or host)..":");
444 local modules = array.collect(keys(modulemanager.get_modules(host) or {})):sort();
445 if #modules == 0 then
446 if prosody.hosts[host] then
447 print(" No modules loaded");
449 print(" Host not found");
452 for _, name in ipairs(modules) do
460 function def_env.config:load(filename, format)
461 local config_load = require "core.configmanager".load;
462 local ok, err = config_load(filename, format);
464 return false, err or "Unknown error loading config";
466 return true, "Config loaded";
469 function def_env.config:get(host, section, key)
470 local config_get = require "core.configmanager".get
471 return true, tostring(config_get(host, section, key));
474 function def_env.config:reload()
475 local ok, err = prosody.reload_config();
476 return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
480 function def_env.hosts:list()
481 for host, host_session in pairs(hosts) do
482 self.session.print(host);
487 function def_env.hosts:add(name)
492 local function show_c2s(callback)
493 for hostname, host in pairs(hosts) do
494 for username, user in pairs(host.sessions or {}) do
495 for resource, session in pairs(user.sessions or {}) do
496 local jid = username.."@"..hostname.."/"..resource;
497 callback(jid, session);
503 function def_env.c2s:count(match_jid)
505 show_c2s(function (jid, session)
506 if (not match_jid) or jid:match(match_jid) then
510 return true, "Total: "..count.." clients";
513 function def_env.c2s:show(match_jid)
514 local print, count = self.session.print, 0;
516 show_c2s(function (jid, session)
517 if curr_host ~= session.host then
518 curr_host = session.host;
521 if (not match_jid) or jid:match(match_jid) then
523 local status, priority = "unavailable", tostring(session.priority or "-");
524 if session.presence then
525 status = session.presence:child_with_name("show");
527 status = status:get_text() or "[invalid!]";
529 status = "available";
532 print(" "..jid.." - "..status.."("..priority..")");
535 return true, "Total: "..count.." clients";
538 function def_env.c2s:show_insecure(match_jid)
539 local print, count = self.session.print, 0;
540 show_c2s(function (jid, session)
541 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
546 return true, "Total: "..count.." insecure client connections";
549 function def_env.c2s:show_secure(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 session.secure then
557 return true, "Total: "..count.." secure client connections";
560 function def_env.c2s:close(match_jid)
562 show_c2s(function (jid, session)
563 if jid == match_jid or jid_bare(jid) == match_jid then
568 return true, "Total: "..count.." sessions closed";
571 local function session_flags(session, line)
572 if session.cert_identity_status == "valid" then
573 line[#line+1] = "(secure)";
574 elseif session.secure then
575 line[#line+1] = "(encrypted)";
577 if session.compressed then
578 line[#line+1] = "(compressed)";
580 if session.smacks then
581 line[#line+1] = "(sm)";
583 if session.conn and session.conn:ip():match(":") then
584 line[#line+1] = "(IPv6)";
586 return table.concat(line, " ");
590 function def_env.s2s:show(match_jid)
591 local _print = self.session.print;
592 local print = self.session.print;
594 local count_in, count_out = 0,0;
596 for host, host_session in pairs(hosts) do
597 print = function (...) _print(host); _print(...); print = _print; end
598 for remotehost, session in pairs(host_session.s2sout) do
599 if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
600 count_out = count_out + 1;
601 print(session_flags(session, {" ", host, "->", remotehost}));
602 if session.sendq then
603 print(" There are "..#session.sendq.." queued outgoing stanzas for this connection");
605 if session.type == "s2sout_unauthed" then
606 if session.connecting then
607 print(" Connection not yet established");
608 if not session.srv_hosts then
609 if not session.conn then
610 print(" We do not yet have a DNS answer for this host's SRV records");
612 print(" This host has no SRV records, using A record instead");
614 elseif session.srv_choice then
615 print(" We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
616 local srv_choice = session.srv_hosts[session.srv_choice];
617 print(" Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
619 elseif session.notopen then
620 print(" The <stream> has not yet been opened");
621 elseif not session.dialback_key then
622 print(" Dialback has not been initiated yet");
623 elseif session.dialback_key then
624 print(" Dialback has been requested, but no result received");
629 local subhost_filter = function (h)
630 return (match_jid and h:match(match_jid));
632 for session in pairs(incoming_s2s) do
633 if session.to_host == host and ((not match_jid) or host:match(match_jid)
634 or (session.from_host and session.from_host:match(match_jid))
635 -- Pft! is what I say to list comprehensions
636 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
637 count_in = count_in + 1;
638 print(session_flags(session, {" ", host, "<-", session.from_host or "(unknown)"}));
639 if session.type == "s2sin_unauthed" then
640 print(" Connection not yet authenticated");
642 for name in pairs(session.hosts) do
643 if name ~= session.from_host then
644 print(" also hosts "..tostring(name));
653 for session in pairs(incoming_s2s) do
654 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
655 count_in = count_in + 1;
656 print("Other incoming s2s connections");
657 print(" (unknown) <- "..(session.from_host or "(unknown)"));
661 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
664 local function print_subject(print, subject)
665 for _, entry in ipairs(subject) do
668 entry.name or entry.oid,
669 entry.value:gsub("[\r\n%z%c]", " ")
675 -- As much as it pains me to use the 0-based depths that OpenSSL does,
676 -- I think there's going to be more confusion among operators if we
678 local function print_errors(print, errors)
679 for depth, t in pairs(errors) do
683 table.concat(t, "\n| ")
689 function def_env.s2s:showcert(domain)
690 local ser = require "util.serialization".serialize;
691 local print = self.session.print;
692 local domain_sessions = set.new(array.collect(keys(incoming_s2s)))
693 /function(session) return session.from_host == domain and session or nil; end;
694 for local_host in values(prosody.hosts) do
695 local s2sout = local_host.s2sout;
696 if s2sout and s2sout[domain] then
697 domain_sessions:add(s2sout[domain]);
701 for session in domain_sessions do
702 local conn = session.conn;
703 conn = conn and conn:socket();
704 if not conn.getpeerchain then
705 if conn.dohandshake then
706 error("This version of LuaSec does not support certificate viewing");
709 local cert = conn:getpeercertificate();
711 local certs = conn:getpeerchain();
712 local digest = cert:digest("sha1");
713 if not cert_set[digest] then
714 local chain_valid, chain_errors = conn:getpeerverification();
717 from = session.from_host,
718 to = session.to_host,
719 direction = session.direction
721 chain_valid = chain_valid;
722 chain_errors = chain_errors;
726 table.insert(cert_set[digest], {
727 from = session.from_host,
728 to = session.to_host,
729 direction = session.direction
735 local domain_certs = array.collect(values(cert_set));
736 -- Phew. We now have a array of unique certificates presented by domain.
737 local n_certs = #domain_certs;
740 return "No certificates found for "..domain;
743 local function _capitalize_and_colon(byte)
744 return string.upper(byte)..":";
746 local function pretty_fingerprint(hash)
747 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
750 for cert_info in values(domain_certs) do
751 local certs = cert_info.certs;
752 local cert = certs[1];
754 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
756 local n_streams = #cert_info;
757 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
758 for _, stream in ipairs(cert_info) do
759 if stream.direction == "incoming" then
760 print(" "..stream.to.." <- "..stream.from);
762 print(" "..stream.from.." -> "..stream.to);
766 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
767 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
769 print("Trusted certificate: Yes");
771 print("Trusted certificate: No");
772 print_errors(print, errors);
776 print_subject(print, cert:issuer());
778 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
780 print_subject(print, cert:subject());
783 return ("Showing "..n_certs.." certificate"
784 ..(n_certs==1 and "" or "s")
785 .." presented by "..domain..".");
788 function def_env.s2s:close(from, to)
789 local print, count = self.session.print, 0;
791 if not (from and to) then
792 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
793 elseif from == to then
794 return false, "Both from and to are the same... you can't do that :)";
797 if hosts[from] and not hosts[to] then
798 -- Is an outgoing connection
799 local session = hosts[from].s2sout[to];
801 print("No outgoing connection from "..from.." to "..to)
803 (session.close or s2smanager.destroy_session)(session);
805 print("Closed outgoing session from "..from.." to "..to);
807 elseif hosts[to] and not hosts[from] then
808 -- Is an incoming connection
809 for session in pairs(incoming_s2s) do
810 if session.to_host == to and session.from_host == from then
811 (session.close or s2smanager.destroy_session)(session);
817 print("No incoming connections from "..from.." to "..to);
819 print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
821 elseif hosts[to] and hosts[from] then
822 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
824 return false, "Neither of the hostnames you specified are being used on this server";
827 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
830 function def_env.s2s:closeall(host)
833 if not host or type(host) ~= "string" then return false, "wrong syntax: please use s2s:closeall('hostname.tld')"; end
835 for session in pairs(incoming_s2s) do
836 if session.to_host == host then
837 (session.close or s2smanager.destroy_session)(session);
841 for _, session in pairs(hosts[host].s2sout) do
842 (session.close or s2smanager.destroy_session)(session);
846 for session in pairs(incoming_s2s) do
847 if session.from_host == host then
848 (session.close or s2smanager.destroy_session)(session);
852 for _, h in pairs(hosts) do
853 if h.s2sout[host] then
854 (h.s2sout[host].close or s2smanager.destroy_session)(h.s2sout[host]);
860 if count == 0 then return false, "No sessions to close.";
861 else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
864 def_env.host = {}; def_env.hosts = def_env.host;
866 function def_env.host:activate(hostname, config)
867 return hostmanager.activate(hostname, config);
869 function def_env.host:deactivate(hostname, reason)
870 return hostmanager.deactivate(hostname, reason);
873 function def_env.host:list()
874 local print = self.session.print;
876 for host in values(array.collect(keys(prosody.hosts)):sort()) do
880 return true, i.." hosts";
885 function def_env.port:list()
886 local print = self.session.print;
887 local services = portmanager.get_active_services().data;
888 local ordered_services, n_ports = {}, 0;
889 for service, interfaces in pairs(services) do
890 table.insert(ordered_services, service);
892 table.sort(ordered_services);
893 for _, service in ipairs(ordered_services) do
894 local ports_list = {};
895 for interface, ports in pairs(services[service]) do
896 for port in pairs(ports) do
897 table.insert(ports_list, "["..interface.."]:"..port);
900 n_ports = n_ports + #ports_list;
901 print(service..": "..table.concat(ports_list, ", "));
903 return true, #ordered_services.." services listening on "..n_ports.." ports";
906 function def_env.port:close(close_port, close_interface)
907 close_port = assert(tonumber(close_port), "Invalid port number");
909 local services = portmanager.get_active_services().data;
910 for service, interfaces in pairs(services) do
911 for interface, ports in pairs(interfaces) do
912 if not close_interface or close_interface == interface then
913 if ports[close_port] then
914 self.session.print("Closing ["..interface.."]:"..close_port.."...");
915 local ok, err = portmanager.close(interface, close_port)
917 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
919 n_closed = n_closed + 1;
925 return true, "Closed "..n_closed.." ports";
930 local console_room_mt = {
931 __index = function (self, k) return self.room[k]; end;
932 __tostring = function (self)
933 return "MUC room <"..self.room.jid..">";
937 local function check_muc(jid)
938 local room_name, host = jid_split(jid);
939 if not hosts[host] then
940 return nil, "No such host: "..host;
941 elseif not hosts[host].modules.muc then
942 return nil, "Host '"..host.."' is not a MUC service";
944 return room_name, host;
947 function def_env.muc:create(room_jid)
948 local room, host = check_muc(room_jid);
949 if not room_name then
950 return room_name, host;
952 if not room then return nil, host end
953 if hosts[host].modules.muc.rooms[room_jid] then return nil, "Room exists already" end
954 return hosts[host].modules.muc.create_room(room_jid);
957 function def_env.muc:room(room_jid)
958 local room_name, host = check_muc(room_jid);
959 if not room_name then
960 return room_name, host;
962 local room_obj = hosts[host].modules.muc.rooms[room_jid];
964 return nil, "No such room: "..room_jid;
966 return setmetatable({ room = room_obj }, console_room_mt);
969 local um = require"core.usermanager";
972 function def_env.user:create(jid, password)
973 local username, host = jid_split(jid);
974 if not hosts[host] then
975 return nil, "No such host: "..host;
976 elseif um.user_exists(username, host) then
977 return nil, "User exists";
979 local ok, err = um.create_user(username, password, host);
981 return true, "User created";
983 return nil, "Could not create user: "..err;
987 function def_env.user:delete(jid)
988 local username, host = jid_split(jid);
989 if not hosts[host] then
990 return nil, "No such host: "..host;
991 elseif not um.user_exists(username, host) then
992 return nil, "No such user";
994 local ok, err = um.delete_user(username, host);
996 return true, "User deleted";
998 return nil, "Could not delete user: "..err;
1002 function def_env.user:password(jid, password)
1003 local username, host = jid_split(jid);
1004 if not hosts[host] then
1005 return nil, "No such host: "..host;
1006 elseif not um.user_exists(username, host) then
1007 return nil, "No such user";
1009 local ok, err = um.set_password(username, password, host);
1011 return true, "User password changed";
1013 return nil, "Could not change password for user: "..err;
1017 function def_env.user:list(host, pat)
1019 return nil, "No host given";
1020 elseif not hosts[host] then
1021 return nil, "No such host";
1023 local print = self.session.print;
1024 local total, matches = 0, 0;
1025 for user in um.users(host) do
1026 if not pat or user:match(pat) then
1027 print(user.."@"..host);
1028 matches = matches + 1;
1032 return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
1037 local st = require "util.stanza";
1038 function def_env.xmpp:ping(localhost, remotehost)
1039 if hosts[localhost] then
1040 core_post_stanza(hosts[localhost],
1041 st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
1042 :tag("ping", {xmlns="urn:xmpp:ping"}));
1043 return true, "Sent ping";
1045 return nil, "No such host";
1050 local adns = require"net.adns";
1051 local dns = require"net.dns";
1053 function def_env.dns:lookup(name, typ, class)
1054 local ret = "Query sent";
1055 local print = self.session.print;
1056 local function handler(...)
1057 ret = "Got response";
1060 adns.lookup(handler, name, typ, class);
1064 function def_env.dns:addnameserver(...)
1065 dns._resolver:addnameserver(...)
1069 function def_env.dns:setnameserver(...)
1070 dns._resolver:setnameserver(...)
1074 function def_env.dns:purge()
1079 function def_env.dns:cache()
1080 return true, "Cache:\n"..tostring(dns.cache())
1085 function printbanner(session)
1086 local option = module:get_option("console_banner");
1087 if option == nil or option == "full" or option == "graphic" then
1090 | _ \ _ __ ___ ___ _-_ __| |_ _
1091 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1092 | __/| | | (_) \__ \ |_| | (_| | |_| |
1093 |_| |_| \___/|___/\___/ \__,_|\__, |
1094 A study in simplicity |___/
1098 if option == nil or option == "short" or option == "full" then
1099 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1100 session.print("You may find more help on using this console in our online documentation at ");
1101 session.print("http://prosody.im/doc/console\n");
1103 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
1104 if type(option) == "string" then
1105 session.print(option)
1106 elseif type(option) == "function" then
1107 module:log("warn", "Using functions as value for the console_banner option is no longer supported");
1112 module:provides("net", {
1114 listener = console_listener;
1115 default_port = 5582;