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;
21 local console_listener = { default_port = 5582; default_mode = "*a"; interface = "127.0.0.1" };
23 local iterators = require "util.iterators";
24 local keys, values = iterators.keys, iterators.values;
25 local jid_bare, jid_split, jid_join = import("util.jid", "bare", "prepped_split", "join");
26 local set, array = require "util.set", require "util.array";
27 local cert_verify_identity = require "util.x509".verify_identity;
28 local envload = require "util.envload".envload;
29 local envloadfile = require "util.envload".envloadfile;
30 local has_pposix, pposix = pcall(require, "util.pposix");
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.onreadtimeout(conn)
159 local session = sessions[conn];
166 function console_listener.ondisconnect(conn, err)
167 local session = sessions[conn];
169 session.disconnect();
170 sessions[conn] = nil;
174 function console_listener.ondetach(conn)
175 sessions[conn] = nil;
178 -- Console commands --
179 -- These are simple commands, not valid standalone in Lua
181 function commands.bye(session)
182 session.print("See you! :)");
183 session.closed = true;
184 session.disconnect();
186 commands.quit, commands.exit = commands.bye, commands.bye;
188 commands["!"] = function (session, data)
189 if data:match("^!!") and session.env._ then
190 session.print("!> "..session.env._);
191 return console_listener.onincoming(session.conn, session.env._);
193 local old, new = data:match("^!(.-[^\\])!(.-)!$");
195 local ok, res = pcall(string.gsub, session.env._, old, new);
200 session.print("!> "..res);
201 return console_listener.onincoming(session.conn, res);
203 session.print("Sorry, not sure what you want");
207 function commands.help(session, data)
208 local print = session.print;
209 local section = data:match("^help (%w+)");
211 print [[Commands are divided into multiple sections. For help on a particular section, ]]
212 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
214 print [[c2s - Commands to manage local client-to-server sessions]]
215 print [[s2s - Commands to manage sessions between this server and others]]
216 print [[module - Commands to load/reload/unload modules/plugins]]
217 print [[host - Commands to activate, deactivate and list virtual hosts]]
218 print [[user - Commands to create and delete users, and change their passwords]]
219 print [[server - Uptime, version, shutting down, etc.]]
220 print [[port - Commands to manage ports the server is listening on]]
221 print [[dns - Commands to manage and inspect the internal DNS resolver]]
222 print [[config - Reloading the configuration, etc.]]
223 print [[console - Help regarding the console itself]]
224 elseif section == "c2s" then
225 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
226 print [[c2s:show_insecure() - Show all unencrypted client connections]]
227 print [[c2s:show_secure() - Show all encrypted client connections]]
228 print [[c2s:show_tls() - Show TLS cipher info for encrypted sessions]]
229 print [[c2s:close(jid) - Close all sessions for the specified JID]]
230 elseif section == "s2s" then
231 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
232 print [[s2s:show_tls(domain) - Show TLS cipher info for encrypted sessions]]
233 print [[s2s:close(from, to) - Close a connection from one domain to another]]
234 print [[s2s:closeall(host) - Close all the incoming/outgoing s2s sessions to specified host]]
235 elseif section == "module" then
236 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
237 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
238 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
239 print [[module:list(host) - List the modules loaded on the specified host]]
240 elseif section == "host" then
241 print [[host:activate(hostname) - Activates the specified host]]
242 print [[host:deactivate(hostname) - Disconnects all clients on this host and deactivates]]
243 print [[host:list() - List the currently-activated hosts]]
244 elseif section == "user" then
245 print [[user:create(jid, password) - Create the specified user account]]
246 print [[user:password(jid, password) - Set the password for the specified user account]]
247 print [[user:delete(jid) - Permanently remove the specified user account]]
248 print [[user:list(hostname, pattern) - List users on the specified host, optionally filtering with a pattern]]
249 elseif section == "server" then
250 print [[server:version() - Show the server's version number]]
251 print [[server:uptime() - Show how long the server has been running]]
252 print [[server:memory() - Show details about the server's memory usage]]
253 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
254 elseif section == "port" then
255 print [[port:list() - Lists all network ports prosody currently listens on]]
256 print [[port:close(port, interface) - Close a port]]
257 elseif section == "dns" then
258 print [[dns:lookup(name, type, class) - Do a DNS lookup]]
259 print [[dns:addnameserver(nameserver) - Add a nameserver to the list]]
260 print [[dns:setnameserver(nameserver) - Replace the list of name servers with the supplied one]]
261 print [[dns:purge() - Clear the DNS cache]]
262 print [[dns:cache() - Show cached records]]
263 elseif section == "config" then
264 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
265 elseif section == "console" then
266 print [[Hey! Welcome to Prosody's admin console.]]
267 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
268 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
269 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
271 print [[For now we offer a couple of handy shortcuts:]]
272 print [[!! - Repeat the last command]]
273 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
275 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
276 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
277 print [[the running server. Great fun, but be careful not to break anything :)]]
282 -- Session environment --
283 -- Anything in def_env will be accessible within the session as a global variable
285 --luacheck: ignore 212/self
289 function def_env.server:insane_reload()
290 prosody.unlock_globals();
292 prosody = _G.prosody;
293 return true, "Server reloaded";
296 function def_env.server:version()
297 return true, tostring(prosody.version or "unknown");
300 function def_env.server:uptime()
301 local t = os.time()-prosody.start_time;
302 local seconds = t%60;
303 t = (t - seconds)/60;
304 local minutes = t%60;
305 t = (t - minutes)/60;
309 return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
310 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
311 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
314 function def_env.server:shutdown(reason)
315 prosody.shutdown(reason);
316 return true, "Shutdown initiated";
319 local function human(kb)
322 kb, unit = kb/1024, "M";
324 return ("%0.2f%sB"):format(kb, unit);
327 function def_env.server:memory()
328 if not has_pposix or not pposix.meminfo then
329 return true, "Lua is using "..collectgarbage("count");
331 local mem, lua_mem = pposix.meminfo(), collectgarbage("count");
332 local print = self.session.print;
333 print("Process: "..human((mem.allocated+mem.allocated_mmap)/1024));
334 print(" Used: "..human(mem.used/1024).." ("..human(lua_mem).." by Lua)");
335 print(" Free: "..human(mem.unused/1024).." ("..human(mem.returnable/1024).." returnable)");
341 function def_env.timer:info()
342 local socket = require "socket";
343 local print = self.session.print;
344 local add_task = require"util.timer".add_task;
345 local h, params = add_task.h, add_task.params;
347 print("-- util.timer");
348 for i, id in ipairs(h.ids) do
349 if not params[id] then
350 print(os.date("%F %T", h.priorities[i]), h.items[id]);
351 elseif not params[id].callback then
352 print(os.date("%F %T", h.priorities[i]), h.items[id], unpack(params[id]));
354 print(os.date("%F %T", h.priorities[i]), params[id].callback, unpack(params[id]));
358 if server.event_base then
360 for k, v in pairs(debug.getregistry()) do
361 if type(v) == "function" and v.callback and v.callback == add_task._on_timer then
365 print(count .. " libevent callbacks");
368 local next_time = h:peek();
370 return true, os.date("Next event at %F %T (in %%.6fs)", next_time):format(next_time - socket.gettime());
378 local function get_hosts_set(hosts, module)
379 if type(hosts) == "table" then
381 return set.new(hosts);
382 elseif hosts._items then
385 elseif type(hosts) == "string" then
386 return set.new { hosts };
387 elseif hosts == nil then
388 local hosts_set = set.new(array.collect(keys(prosody.hosts)))
389 / function (host) return (prosody.hosts[host].type == "local" or module and modulemanager.is_loaded(host, module)) and host or nil; end;
390 if module and modulemanager.get_module("*", module) then
397 function def_env.module:load(name, hosts, config)
398 hosts = get_hosts_set(hosts);
400 -- Load the module for each host
401 local ok, err, count, mod = true, nil, 0, nil;
403 if (not modulemanager.is_loaded(host, name)) then
404 mod, err = modulemanager.load(host, name, config);
407 if err == "global-module-already-loaded" then
409 ok, err, count = true, nil, 1;
413 self.session.print(err or "Unknown error loading module");
416 self.session.print("Loaded for "..mod.module.host);
421 return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
424 function def_env.module:unload(name, hosts)
425 hosts = get_hosts_set(hosts, name);
427 -- Unload the module for each host
428 local ok, err, count = true, nil, 0;
430 if modulemanager.is_loaded(host, name) then
431 ok, err = modulemanager.unload(host, name);
434 self.session.print(err or "Unknown error unloading module");
437 self.session.print("Unloaded from "..host);
441 return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
444 function def_env.module:reload(name, hosts)
445 hosts = array.collect(get_hosts_set(hosts, name)):sort(function (a, b)
446 if a == "*" then return true
447 elseif b == "*" then return false
448 else return a < b; end
451 -- Reload the module for each host
452 local ok, err, count = true, nil, 0;
453 for _, host in ipairs(hosts) do
454 if modulemanager.is_loaded(host, name) then
455 ok, err = modulemanager.reload(host, name);
458 self.session.print(err or "Unknown error reloading module");
464 self.session.print("Reloaded on "..host);
468 return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
471 function def_env.module:list(hosts)
473 hosts = array.collect(keys(prosody.hosts));
474 table.insert(hosts, 1, "*");
476 if type(hosts) == "string" then
479 if type(hosts) ~= "table" then
480 return false, "Please supply a host or a list of hosts you would like to see";
483 local print = self.session.print;
484 for _, host in ipairs(hosts) do
485 print((host == "*" and "Global" or host)..":");
486 local modules = array.collect(keys(modulemanager.get_modules(host) or {})):sort();
487 if #modules == 0 then
488 if prosody.hosts[host] then
489 print(" No modules loaded");
491 print(" Host not found");
494 for _, name in ipairs(modules) do
502 function def_env.config:load(filename, format)
503 local config_load = require "core.configmanager".load;
504 local ok, err = config_load(filename, format);
506 return false, err or "Unknown error loading config";
508 return true, "Config loaded";
511 function def_env.config:get(host, section, key)
512 local config_get = require "core.configmanager".get
513 return true, tostring(config_get(host, section, key));
516 function def_env.config:reload()
517 local ok, err = prosody.reload_config();
518 return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
521 local function common_info(session, line)
523 line[#line+1] = "["..session.id.."]"
525 line[#line+1] = "["..session.type..(tostring(session):match("%x*$")).."]"
529 local function session_flags(session, line)
531 common_info(session, line);
532 if session.type == "c2s" then
533 local status, priority = "unavailable", tostring(session.priority or "-");
534 if session.presence then
535 status = session.presence:get_child_text("show") or "available";
537 line[#line+1] = status.."("..priority..")";
539 if session.cert_identity_status == "valid" then
540 line[#line+1] = "(authenticated)";
542 if session.secure then
543 line[#line+1] = "(encrypted)";
545 if session.compressed then
546 line[#line+1] = "(compressed)";
548 if session.smacks then
549 line[#line+1] = "(sm)";
551 if session.ip and session.ip:match(":") then
552 line[#line+1] = "(IPv6)";
554 if session.remote then
555 line[#line+1] = "(remote)";
557 return table.concat(line, " ");
560 local function tls_info(session, line)
562 common_info(session, line);
563 if session.secure then
564 local sock = session.conn and session.conn.socket and session.conn:socket();
565 if sock and sock.info then
566 local info = sock:info();
567 line[#line+1] = ("(%s with %s)"):format(info.protocol, info.cipher);
569 line[#line+1] = "(cipher info unavailable)";
572 line[#line+1] = "(insecure)";
574 return table.concat(line, " ");
579 local function get_jid(session)
580 if session.username then
581 return session.full_jid or jid_join(session.username, session.host, session.resource);
584 local conn = session.conn;
585 local ip = session.ip or "?";
586 local clientport = conn and conn:clientport() or "?";
587 local serverip = conn and conn.server and conn:server():ip() or "?";
588 local serverport = conn and conn:serverport() or "?"
589 return jid_join("["..ip.."]:"..clientport, session.host or "["..serverip.."]:"..serverport);
592 local function show_c2s(callback)
593 local c2s = array.collect(values(module:shared"/*/c2s/sessions"));
594 c2s:sort(function(a, b)
595 if a.host == b.host then
596 if a.username == b.username then
597 return (a.resource or "") > (b.resource or "");
599 return (a.username or "") > (b.username or "");
601 return (a.host or "") > (b.host or "");
602 end):map(function (session)
603 callback(get_jid(session), session)
607 function def_env.c2s:count(match_jid)
608 return true, "Total: ".. iterators.count(values(module:shared"/*/c2s/sessions")) .." clients";
611 function def_env.c2s:show(match_jid, annotate)
612 local print, count = self.session.print, 0;
613 annotate = annotate or session_flags;
614 local curr_host = false;
615 show_c2s(function (jid, session)
616 if curr_host ~= session.host then
617 curr_host = session.host;
618 print(curr_host or "(not connected to any host yet)");
620 if (not match_jid) or jid:match(match_jid) then
622 print(annotate(session, { " ", jid }));
625 return true, "Total: "..count.." clients";
628 function def_env.c2s:show_insecure(match_jid)
629 local print, count = self.session.print, 0;
630 show_c2s(function (jid, session)
631 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
636 return true, "Total: "..count.." insecure client connections";
639 function def_env.c2s:show_secure(match_jid)
640 local print, count = self.session.print, 0;
641 show_c2s(function (jid, session)
642 if ((not match_jid) or jid:match(match_jid)) and session.secure then
647 return true, "Total: "..count.." secure client connections";
650 function def_env.c2s:show_tls(match_jid)
651 return self:show(match_jid, tls_info);
654 function def_env.c2s:close(match_jid)
656 show_c2s(function (jid, session)
657 if jid == match_jid or jid_bare(jid) == match_jid then
662 return true, "Total: "..count.." sessions closed";
667 function def_env.s2s:show(match_jid, annotate)
668 local print = self.session.print;
669 annotate = annotate or session_flags;
671 local count_in, count_out = 0,0;
672 local s2s_list = { };
674 local s2s_sessions = module:shared"/*/s2s/sessions";
675 for _, session in pairs(s2s_sessions) do
676 local remotehost, localhost, direction;
677 if session.direction == "outgoing" then
679 count_out = count_out + 1;
680 remotehost, localhost = session.to_host or "?", session.from_host or "?";
683 count_in = count_in + 1;
684 remotehost, localhost = session.from_host or "?", session.to_host or "?";
686 local sess_lines = { l = localhost, r = remotehost,
687 annotate(session, { "", direction, remotehost or "?" })};
689 if (not match_jid) or remotehost:match(match_jid) or localhost:match(match_jid) then
690 table.insert(s2s_list, sess_lines);
691 local print = function (s) table.insert(sess_lines, " "..s); end
692 if session.sendq then
693 print("There are "..#session.sendq.." queued outgoing stanzas for this connection");
695 if session.type == "s2sout_unauthed" then
696 if session.connecting then
697 print("Connection not yet established");
698 if not session.srv_hosts then
699 if not session.conn then
700 print("We do not yet have a DNS answer for this host's SRV records");
702 print("This host has no SRV records, using A record instead");
704 elseif session.srv_choice then
705 print("We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
706 local srv_choice = session.srv_hosts[session.srv_choice];
707 print("Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
709 elseif session.notopen then
710 print("The <stream> has not yet been opened");
711 elseif not session.dialback_key then
712 print("Dialback has not been initiated yet");
713 elseif session.dialback_key then
714 print("Dialback has been requested, but no result received");
717 if session.type == "s2sin_unauthed" then
718 print("Connection not yet authenticated");
719 elseif session.type == "s2sin" then
720 for name in pairs(session.hosts) do
721 if name ~= session.from_host then
722 print("also hosts "..tostring(name));
729 -- Sort by local host, then remote host
730 table.sort(s2s_list, function(a,b)
731 if a.l == b.l then return a.r < b.r; end
735 for _, sess_lines in ipairs(s2s_list) do
736 if sess_lines.l ~= lasthost then print(sess_lines.l); lasthost=sess_lines.l end
737 for _, line in ipairs(sess_lines) do print(line); end
739 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
742 function def_env.s2s:show_tls(match_jid)
743 return self:show(match_jid, tls_info);
746 local function print_subject(print, subject)
747 for _, entry in ipairs(subject) do
750 entry.name or entry.oid,
751 entry.value:gsub("[\r\n%z%c]", " ")
757 -- As much as it pains me to use the 0-based depths that OpenSSL does,
758 -- I think there's going to be more confusion among operators if we
760 local function print_errors(print, errors)
761 for depth, t in pairs(errors) do
765 table.concat(t, "\n| ")
771 function def_env.s2s:showcert(domain)
772 local ser = require "util.serialization".serialize;
773 local print = self.session.print;
774 local s2s_sessions = module:shared"/*/s2s/sessions";
775 local domain_sessions = set.new(array.collect(values(s2s_sessions)))
776 /function(session) return (session.to_host == domain or session.from_host == domain) and session or nil; end;
778 for session in domain_sessions do
779 local conn = session.conn;
780 conn = conn and conn:socket();
781 if not conn.getpeerchain then
782 if conn.dohandshake then
783 error("This version of LuaSec does not support certificate viewing");
786 local cert = conn:getpeercertificate();
788 local certs = conn:getpeerchain();
789 local digest = cert:digest("sha1");
790 if not cert_set[digest] then
791 local chain_valid, chain_errors = conn:getpeerverification();
794 from = session.from_host,
795 to = session.to_host,
796 direction = session.direction
798 chain_valid = chain_valid;
799 chain_errors = chain_errors;
803 table.insert(cert_set[digest], {
804 from = session.from_host,
805 to = session.to_host,
806 direction = session.direction
812 local domain_certs = array.collect(values(cert_set));
813 -- Phew. We now have a array of unique certificates presented by domain.
814 local n_certs = #domain_certs;
817 return "No certificates found for "..domain;
820 local function _capitalize_and_colon(byte)
821 return string.upper(byte)..":";
823 local function pretty_fingerprint(hash)
824 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
827 for cert_info in values(domain_certs) do
828 local certs = cert_info.certs;
829 local cert = certs[1];
831 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
833 local n_streams = #cert_info;
834 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
835 for _, stream in ipairs(cert_info) do
836 if stream.direction == "incoming" then
837 print(" "..stream.to.." <- "..stream.from);
839 print(" "..stream.from.." -> "..stream.to);
843 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
844 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
846 print("Trusted certificate: Yes");
848 print("Trusted certificate: No");
849 print_errors(print, errors);
853 print_subject(print, cert:issuer());
855 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
857 print_subject(print, cert:subject());
860 return ("Showing "..n_certs.." certificate"
861 ..(n_certs==1 and "" or "s")
862 .." presented by "..domain..".");
865 function def_env.s2s:close(from, to)
866 local print, count = self.session.print, 0;
867 local s2s_sessions = module:shared"/*/s2s/sessions";
870 if from and not to then
871 match_id, from = from;
873 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
874 elseif from == to then
875 return false, "Both from and to are the same... you can't do that :)";
878 for _, session in pairs(s2s_sessions) do
879 local id = session.type..tostring(session):match("[a-f0-9]+$");
880 if (match_id and match_id == id)
881 or (session.from_host == from and session.to_host == to) then
882 print(("Closing connection from %s to %s [%s]"):format(session.from_host, session.to_host, id));
883 (session.close or s2smanager.destroy_session)(session);
887 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
890 function def_env.s2s:closeall(host)
892 local s2s_sessions = module:shared"/*/s2s/sessions";
893 for _,session in pairs(s2s_sessions) do
894 if not host or session.from_host == host or session.to_host == host then
899 if count == 0 then return false, "No sessions to close.";
900 else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
903 def_env.host = {}; def_env.hosts = def_env.host;
905 function def_env.host:activate(hostname, config)
906 return hostmanager.activate(hostname, config);
908 function def_env.host:deactivate(hostname, reason)
909 return hostmanager.deactivate(hostname, reason);
912 function def_env.host:list()
913 local print = self.session.print;
916 for host in values(array.collect(keys(prosody.hosts)):sort()) do
918 type = hosts[host].type;
919 if type == "local" then
922 type = module:context(host):get_option_string("component_module", type);
923 if type ~= "component" then
924 type = type .. " component";
926 print(("%s (%s)"):format(host, type));
929 return true, i.." hosts";
934 function def_env.port:list()
935 local print = self.session.print;
936 local services = portmanager.get_active_services().data;
937 local ordered_services, n_ports = {}, 0;
938 for service, interfaces in pairs(services) do
939 table.insert(ordered_services, service);
941 table.sort(ordered_services);
942 for _, service in ipairs(ordered_services) do
943 local ports_list = {};
944 for interface, ports in pairs(services[service]) do
945 for port in pairs(ports) do
946 table.insert(ports_list, "["..interface.."]:"..port);
949 n_ports = n_ports + #ports_list;
950 print(service..": "..table.concat(ports_list, ", "));
952 return true, #ordered_services.." services listening on "..n_ports.." ports";
955 function def_env.port:close(close_port, close_interface)
956 close_port = assert(tonumber(close_port), "Invalid port number");
958 local services = portmanager.get_active_services().data;
959 for service, interfaces in pairs(services) do
960 for interface, ports in pairs(interfaces) do
961 if not close_interface or close_interface == interface then
962 if ports[close_port] then
963 self.session.print("Closing ["..interface.."]:"..close_port.."...");
964 local ok, err = portmanager.close(interface, close_port)
966 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
968 n_closed = n_closed + 1;
974 return true, "Closed "..n_closed.." ports";
979 local console_room_mt = {
980 __index = function (self, k) return self.room[k]; end;
981 __tostring = function (self)
982 return "MUC room <"..self.room.jid..">";
986 local function check_muc(jid)
987 local room_name, host = jid_split(jid);
988 if not hosts[host] then
989 return nil, "No such host: "..host;
990 elseif not hosts[host].modules.muc then
991 return nil, "Host '"..host.."' is not a MUC service";
993 return room_name, host;
996 function def_env.muc:create(room_jid)
997 local room, host = check_muc(room_jid);
998 if not room_name then
999 return room_name, host;
1001 if not room then return nil, host end
1002 if hosts[host].modules.muc.rooms[room_jid] then return nil, "Room exists already" end
1003 return hosts[host].modules.muc.create_room(room_jid);
1006 function def_env.muc:room(room_jid)
1007 local room_name, host = check_muc(room_jid);
1008 if not room_name then
1009 return room_name, host;
1011 local room_obj = hosts[host].modules.muc.get_room_from_jid(room_jid);
1012 if not room_obj then
1013 return nil, "No such room: "..room_jid;
1015 return setmetatable({ room = room_obj }, console_room_mt);
1018 function def_env.muc:list(host)
1019 local host_session = hosts[host];
1020 if not host_session or not host_session.modules.muc then
1021 return nil, "Please supply the address of a local MUC component";
1023 local print = self.session.print;
1025 for room in host_session.modules.muc.each_room() do
1029 return true, c.." rooms";
1032 local um = require"core.usermanager";
1035 function def_env.user:create(jid, password)
1036 local username, host = jid_split(jid);
1037 if not hosts[host] then
1038 return nil, "No such host: "..host;
1039 elseif um.user_exists(username, host) then
1040 return nil, "User exists";
1042 local ok, err = um.create_user(username, password, host);
1044 return true, "User created";
1046 return nil, "Could not create user: "..err;
1050 function def_env.user:delete(jid)
1051 local username, host = jid_split(jid);
1052 if not hosts[host] then
1053 return nil, "No such host: "..host;
1054 elseif not um.user_exists(username, host) then
1055 return nil, "No such user";
1057 local ok, err = um.delete_user(username, host);
1059 return true, "User deleted";
1061 return nil, "Could not delete user: "..err;
1065 function def_env.user:password(jid, password)
1066 local username, host = jid_split(jid);
1067 if not hosts[host] then
1068 return nil, "No such host: "..host;
1069 elseif not um.user_exists(username, host) then
1070 return nil, "No such user";
1072 local ok, err = um.set_password(username, password, host);
1074 return true, "User password changed";
1076 return nil, "Could not change password for user: "..err;
1080 function def_env.user:list(host, pat)
1082 return nil, "No host given";
1083 elseif not hosts[host] then
1084 return nil, "No such host";
1086 local print = self.session.print;
1087 local total, matches = 0, 0;
1088 for user in um.users(host) do
1089 if not pat or user:match(pat) then
1090 print(user.."@"..host);
1091 matches = matches + 1;
1095 return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
1100 local st = require "util.stanza";
1101 function def_env.xmpp:ping(localhost, remotehost)
1102 if hosts[localhost] then
1103 core_post_stanza(hosts[localhost],
1104 st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
1105 :tag("ping", {xmlns="urn:xmpp:ping"}));
1106 return true, "Sent ping";
1108 return nil, "No such host";
1113 local adns = require"net.adns";
1114 local dns = require"net.dns";
1116 function def_env.dns:lookup(name, typ, class)
1117 local ret = "Query sent";
1118 local print = self.session.print;
1119 local function handler(...)
1120 ret = "Got response";
1123 adns.lookup(handler, name, typ, class);
1127 function def_env.dns:addnameserver(...)
1128 dns._resolver:addnameserver(...)
1132 function def_env.dns:setnameserver(...)
1133 dns._resolver:setnameserver(...)
1137 function def_env.dns:purge()
1142 function def_env.dns:cache()
1143 return true, "Cache:\n"..tostring(dns.cache())
1148 function def_env.http:list()
1149 local print = self.session.print;
1151 for host in pairs(prosody.hosts) do
1152 local http_apps = modulemanager.get_items("http-provider", host);
1153 if #http_apps > 0 then
1154 local http_host = module:context(host):get_option("http_host");
1155 print("HTTP endpoints on "..host..(http_host and (" (using "..http_host.."):") or ":"));
1156 for _, provider in ipairs(http_apps) do
1157 local url = module:context(host):http_url(provider.name);
1164 local default_host = module:get_option("http_default_host");
1165 if not default_host then
1166 print("HTTP requests to unknown hosts will return 404 Not Found");
1168 print("HTTP requests to unknown hosts will be handled by "..default_host);
1175 function printbanner(session)
1176 local option = module:get_option_string("console_banner", "full");
1177 if option == "full" or option == "graphic" then
1180 | _ \ _ __ ___ ___ _-_ __| |_ _
1181 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1182 | __/| | | (_) \__ \ |_| | (_| | |_| |
1183 |_| |_| \___/|___/\___/ \__,_|\__, |
1184 A study in simplicity |___/
1188 if option == "short" or option == "full" then
1189 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1190 session.print("You may find more help on using this console in our online documentation at ");
1191 session.print("https://prosody.im/doc/console\n");
1193 if option ~= "short" and option ~= "full" and option ~= "graphic" then
1194 session.print(option);
1198 module:provides("net", {
1200 listener = console_listener;
1201 default_port = 5582;