MUC: Fix delay@from to be room JID (fixes #1416)
[prosody.git] / plugins / mod_admin_telnet.lua
blob1cbe27a42baf818e0ee6cfd1a419fbfd09e6662e
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8 -- luacheck: ignore 212/self
10 module:set_global();
12 local hostmanager = require "core.hostmanager";
13 local modulemanager = require "core.modulemanager";
14 local s2smanager = require "core.s2smanager";
15 local portmanager = require "core.portmanager";
16 local helpers = require "util.helpers";
17 local server = require "net.server";
19 local _G = _G;
21 local prosody = _G.prosody;
23 local console_listener = { default_port = 5582; default_mode = "*a"; interface = "127.0.0.1" };
25 local iterators = require "util.iterators";
26 local keys, values = iterators.keys, iterators.values;
27 local jid_bare, jid_split, jid_join = import("util.jid", "bare", "prepped_split", "join");
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;
32 local has_pposix, pposix = pcall(require, "util.pposix");
34 local commands = module:shared("commands")
35 local def_env = module:shared("env");
36 local default_env_mt = { __index = def_env };
38 local function redirect_output(target, session)
39 local env = setmetatable({ print = session.print }, { __index = function (_, k) return rawget(target, k); end });
40 env.dofile = function(name)
41 local f, err = envloadfile(name, env);
42 if not f then return f, err; end
43 return f();
44 end;
45 return env;
46 end
48 console = {};
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 (...)
55 local t = {};
56 for i=1,select("#", ...) do
57 t[i] = tostring(select(i, ...));
58 end
59 w("| "..table.concat(t, "\t").."\n");
60 end;
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 });
69 end
70 end
72 return session;
73 end
75 function console:process_line(session, line)
76 local useglobalenv;
78 if line:match("^>") then
79 line = line:gsub("^>", "");
80 useglobalenv = true;
81 elseif line == "\004" then
82 commands["bye"](session, line);
83 return;
84 else
85 local command = line:match("^%w+") or line:match("%p");
86 if commands[command] then
87 commands[command](session, line);
88 return;
89 end
90 end
92 session.env._ = 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);
97 if not chunk then
98 chunk, err = envload(line, chunkname, env);
99 if not chunk then
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);
104 return;
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);
112 return;
115 if not ranok then
116 session.print("Fatal error while running command, it did not complete");
117 session.print("Error: "..taskok);
118 return;
121 if not message then
122 session.print("Result: "..tostring(taskok));
123 return;
124 elseif (not taskok) and message then
125 session.print("Command completed with a problem");
126 session.print("Message: "..tostring(message));
127 return;
130 session.print("OK: "..tostring(message));
133 local sessions = {};
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;
147 if partial then
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.onreadtimeout(conn)
160 local session = sessions[conn];
161 if session then
162 session.send("\0");
163 return true;
167 function console_listener.ondisconnect(conn, err) -- luacheck: ignore 212/err
168 local session = sessions[conn];
169 if session then
170 session.disconnect();
171 sessions[conn] = nil;
175 function console_listener.ondetach(conn)
176 sessions[conn] = nil;
179 -- Console commands --
180 -- These are simple commands, not valid standalone in Lua
182 function commands.bye(session)
183 session.print("See you! :)");
184 session.closed = true;
185 session.disconnect();
187 commands.quit, commands.exit = commands.bye, commands.bye;
189 commands["!"] = function (session, data)
190 if data:match("^!!") and session.env._ then
191 session.print("!> "..session.env._);
192 return console_listener.onincoming(session.conn, session.env._);
194 local old, new = data:match("^!(.-[^\\])!(.-)!$");
195 if old and new then
196 local ok, res = pcall(string.gsub, session.env._, old, new);
197 if not ok then
198 session.print(res)
199 return;
201 session.print("!> "..res);
202 return console_listener.onincoming(session.conn, res);
204 session.print("Sorry, not sure what you want");
208 function commands.help(session, data)
209 local print = session.print;
210 local section = data:match("^help (%w+)");
211 if not section then
212 print [[Commands are divided into multiple sections. For help on a particular section, ]]
213 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
214 print [[]]
215 print [[c2s - Commands to manage local client-to-server sessions]]
216 print [[s2s - Commands to manage sessions between this server and others]]
217 print [[module - Commands to load/reload/unload modules/plugins]]
218 print [[host - Commands to activate, deactivate and list virtual hosts]]
219 print [[user - Commands to create and delete users, and change their passwords]]
220 print [[server - Uptime, version, shutting down, etc.]]
221 print [[port - Commands to manage ports the server is listening on]]
222 print [[dns - Commands to manage and inspect the internal DNS resolver]]
223 print [[config - Reloading the configuration, etc.]]
224 print [[console - Help regarding the console itself]]
225 elseif section == "c2s" then
226 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
227 print [[c2s:show_insecure() - Show all unencrypted client connections]]
228 print [[c2s:show_secure() - Show all encrypted client connections]]
229 print [[c2s:show_tls() - Show TLS cipher info for encrypted sessions]]
230 print [[c2s:close(jid) - Close all sessions for the specified JID]]
231 elseif section == "s2s" then
232 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
233 print [[s2s:show_tls(domain) - Show TLS cipher info for encrypted sessions]]
234 print [[s2s:close(from, to) - Close a connection from one domain to another]]
235 print [[s2s:closeall(host) - Close all the incoming/outgoing s2s sessions to specified host]]
236 elseif section == "module" then
237 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
238 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
239 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
240 print [[module:list(host) - List the modules loaded on the specified host]]
241 elseif section == "host" then
242 print [[host:activate(hostname) - Activates the specified host]]
243 print [[host:deactivate(hostname) - Disconnects all clients on this host and deactivates]]
244 print [[host:list() - List the currently-activated hosts]]
245 elseif section == "user" then
246 print [[user:create(jid, password) - Create the specified user account]]
247 print [[user:password(jid, password) - Set the password for the specified user account]]
248 print [[user:delete(jid) - Permanently remove the specified user account]]
249 print [[user:list(hostname, pattern) - List users on the specified host, optionally filtering with a pattern]]
250 elseif section == "server" then
251 print [[server:version() - Show the server's version number]]
252 print [[server:uptime() - Show how long the server has been running]]
253 print [[server:memory() - Show details about the server's memory usage]]
254 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
255 elseif section == "port" then
256 print [[port:list() - Lists all network ports prosody currently listens on]]
257 print [[port:close(port, interface) - Close a port]]
258 elseif section == "dns" then
259 print [[dns:lookup(name, type, class) - Do a DNS lookup]]
260 print [[dns:addnameserver(nameserver) - Add a nameserver to the list]]
261 print [[dns:setnameserver(nameserver) - Replace the list of name servers with the supplied one]]
262 print [[dns:purge() - Clear the DNS cache]]
263 print [[dns:cache() - Show cached records]]
264 elseif section == "config" then
265 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
266 elseif section == "console" then
267 print [[Hey! Welcome to Prosody's admin console.]]
268 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
269 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
270 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
271 print [[]]
272 print [[For now we offer a couple of handy shortcuts:]]
273 print [[!! - Repeat the last command]]
274 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
275 print [[]]
276 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
277 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
278 print [[the running server. Great fun, but be careful not to break anything :)]]
280 print [[]]
283 -- Session environment --
284 -- Anything in def_env will be accessible within the session as a global variable
286 --luacheck: ignore 212/self
288 def_env.server = {};
290 function def_env.server:insane_reload()
291 prosody.unlock_globals();
292 dofile "prosody"
293 prosody = _G.prosody;
294 return true, "Server reloaded";
297 function def_env.server:version()
298 return true, tostring(prosody.version or "unknown");
301 function def_env.server:uptime()
302 local t = os.time()-prosody.start_time;
303 local seconds = t%60;
304 t = (t - seconds)/60;
305 local minutes = t%60;
306 t = (t - minutes)/60;
307 local hours = t%24;
308 t = (t - hours)/24;
309 local days = t;
310 return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
311 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
312 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
315 function def_env.server:shutdown(reason)
316 prosody.shutdown(reason);
317 return true, "Shutdown initiated";
320 local function human(kb)
321 local unit = "K";
322 if kb > 1024 then
323 kb, unit = kb/1024, "M";
325 return ("%0.2f%sB"):format(kb, unit);
328 function def_env.server:memory()
329 if not has_pposix or not pposix.meminfo then
330 return true, "Lua is using "..human(collectgarbage("count"));
332 local mem, lua_mem = pposix.meminfo(), collectgarbage("count");
333 local print = self.session.print;
334 print("Process: "..human((mem.allocated+mem.allocated_mmap)/1024));
335 print(" Used: "..human(mem.used/1024).." ("..human(lua_mem).." by Lua)");
336 print(" Free: "..human(mem.unused/1024).." ("..human(mem.returnable/1024).." returnable)");
337 return true, "OK";
340 def_env.module = {};
342 local function get_hosts_set(hosts, module)
343 if type(hosts) == "table" then
344 if hosts[1] then
345 return set.new(hosts);
346 elseif hosts._items then
347 return hosts;
349 elseif type(hosts) == "string" then
350 return set.new { hosts };
351 elseif hosts == nil then
352 local hosts_set = set.new(array.collect(keys(prosody.hosts)))
353 / function (host) return (prosody.hosts[host].type == "local" or module and modulemanager.is_loaded(host, module)) and host or nil; end;
354 if module and modulemanager.get_module("*", module) then
355 hosts_set:add("*");
357 return hosts_set;
361 function def_env.module:load(name, hosts, config)
362 hosts = get_hosts_set(hosts);
364 -- Load the module for each host
365 local ok, err, count, mod = true, nil, 0;
366 for host in hosts do
367 if (not modulemanager.is_loaded(host, name)) then
368 mod, err = modulemanager.load(host, name, config);
369 if not mod then
370 ok = false;
371 if err == "global-module-already-loaded" then
372 if count > 0 then
373 ok, err, count = true, nil, 1;
375 break;
377 self.session.print(err or "Unknown error loading module");
378 else
379 count = count + 1;
380 self.session.print("Loaded for "..mod.module.host);
385 return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
388 function def_env.module:unload(name, hosts)
389 hosts = get_hosts_set(hosts, name);
391 -- Unload the module for each host
392 local ok, err, count = true, nil, 0;
393 for host in hosts do
394 if modulemanager.is_loaded(host, name) then
395 ok, err = modulemanager.unload(host, name);
396 if not ok then
397 ok = false;
398 self.session.print(err or "Unknown error unloading module");
399 else
400 count = count + 1;
401 self.session.print("Unloaded from "..host);
405 return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
408 local function _sort_hosts(a, b)
409 if a == "*" then return true
410 elseif b == "*" then return false
411 else return a < b; end
414 function def_env.module:reload(name, hosts)
415 hosts = array.collect(get_hosts_set(hosts, name)):sort(_sort_hosts)
417 -- Reload the module for each host
418 local ok, err, count = true, nil, 0;
419 for _, host in ipairs(hosts) do
420 if modulemanager.is_loaded(host, name) then
421 ok, err = modulemanager.reload(host, name);
422 if not ok then
423 ok = false;
424 self.session.print(err or "Unknown error reloading module");
425 else
426 count = count + 1;
427 if ok == nil then
428 ok = true;
430 self.session.print("Reloaded on "..host);
434 return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
437 function def_env.module:list(hosts)
438 if hosts == nil then
439 hosts = array.collect(keys(prosody.hosts));
440 table.insert(hosts, 1, "*");
442 if type(hosts) == "string" then
443 hosts = { hosts };
445 if type(hosts) ~= "table" then
446 return false, "Please supply a host or a list of hosts you would like to see";
449 local print = self.session.print;
450 for _, host in ipairs(hosts) do
451 print((host == "*" and "Global" or host)..":");
452 local modules = array.collect(keys(modulemanager.get_modules(host) or {})):sort();
453 if #modules == 0 then
454 if prosody.hosts[host] then
455 print(" No modules loaded");
456 else
457 print(" Host not found");
459 else
460 for _, name in ipairs(modules) do
461 print(" "..name);
467 def_env.config = {};
468 function def_env.config:load(filename, format)
469 local config_load = require "core.configmanager".load;
470 local ok, err = config_load(filename, format);
471 if not ok then
472 return false, err or "Unknown error loading config";
474 return true, "Config loaded";
477 function def_env.config:get(host, section, key)
478 local config_get = require "core.configmanager".get
479 return true, tostring(config_get(host, section, key));
482 function def_env.config:reload()
483 local ok, err = prosody.reload_config();
484 return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
487 local function common_info(session, line)
488 if session.id then
489 line[#line+1] = "["..session.id.."]"
490 else
491 line[#line+1] = "["..session.type..(tostring(session):match("%x*$")).."]"
495 local function session_flags(session, line)
496 line = line or {};
497 common_info(session, line);
498 if session.type == "c2s" then
499 local status, priority = "unavailable", tostring(session.priority or "-");
500 if session.presence then
501 status = session.presence:get_child_text("show") or "available";
503 line[#line+1] = status.."("..priority..")";
505 if session.cert_identity_status == "valid" then
506 line[#line+1] = "(authenticated)";
508 if session.secure then
509 line[#line+1] = "(encrypted)";
511 if session.compressed then
512 line[#line+1] = "(compressed)";
514 if session.smacks then
515 line[#line+1] = "(sm)";
517 if session.ip and session.ip:match(":") then
518 line[#line+1] = "(IPv6)";
520 if session.remote then
521 line[#line+1] = "(remote)";
523 return table.concat(line, " ");
526 local function tls_info(session, line)
527 line = line or {};
528 common_info(session, line);
529 if session.secure then
530 local sock = session.conn and session.conn.socket and session.conn:socket();
531 if sock and sock.info then
532 local info = sock:info();
533 line[#line+1] = ("(%s with %s)"):format(info.protocol, info.cipher);
534 else
535 line[#line+1] = "(cipher info unavailable)";
537 else
538 line[#line+1] = "(insecure)";
540 return table.concat(line, " ");
543 def_env.c2s = {};
545 local function get_jid(session)
546 if session.username then
547 return session.full_jid or jid_join(session.username, session.host, session.resource);
550 local conn = session.conn;
551 local ip = session.ip or "?";
552 local clientport = conn and conn:clientport() or "?";
553 local serverip = conn and conn.server and conn:server():ip() or "?";
554 local serverport = conn and conn:serverport() or "?"
555 return jid_join("["..ip.."]:"..clientport, session.host or "["..serverip.."]:"..serverport);
558 local function show_c2s(callback)
559 local c2s = array.collect(values(module:shared"/*/c2s/sessions"));
560 c2s:sort(function(a, b)
561 if a.host == b.host then
562 if a.username == b.username then
563 return (a.resource or "") > (b.resource or "");
565 return (a.username or "") > (b.username or "");
567 return (a.host or "") > (b.host or "");
568 end):map(function (session)
569 callback(get_jid(session), session)
570 end);
573 function def_env.c2s:count()
574 return true, "Total: ".. iterators.count(values(module:shared"/*/c2s/sessions")) .." clients";
577 function def_env.c2s:show(match_jid, annotate)
578 local print, count = self.session.print, 0;
579 annotate = annotate or session_flags;
580 local curr_host = false;
581 show_c2s(function (jid, session)
582 if curr_host ~= session.host then
583 curr_host = session.host;
584 print(curr_host or "(not connected to any host yet)");
586 if (not match_jid) or jid:match(match_jid) then
587 count = count + 1;
588 print(annotate(session, { " ", jid }));
590 end);
591 return true, "Total: "..count.." clients";
594 function def_env.c2s:show_insecure(match_jid)
595 local print, count = self.session.print, 0;
596 show_c2s(function (jid, session)
597 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
598 count = count + 1;
599 print(jid);
601 end);
602 return true, "Total: "..count.." insecure client connections";
605 function def_env.c2s:show_secure(match_jid)
606 local print, count = self.session.print, 0;
607 show_c2s(function (jid, session)
608 if ((not match_jid) or jid:match(match_jid)) and session.secure then
609 count = count + 1;
610 print(jid);
612 end);
613 return true, "Total: "..count.." secure client connections";
616 function def_env.c2s:show_tls(match_jid)
617 return self:show(match_jid, tls_info);
620 function def_env.c2s:close(match_jid)
621 local count = 0;
622 show_c2s(function (jid, session)
623 if jid == match_jid or jid_bare(jid) == match_jid then
624 count = count + 1;
625 session:close();
627 end);
628 return true, "Total: "..count.." sessions closed";
632 def_env.s2s = {};
633 function def_env.s2s:show(match_jid, annotate)
634 local print = self.session.print;
635 annotate = annotate or session_flags;
637 local count_in, count_out = 0,0;
638 local s2s_list = { };
640 local s2s_sessions = module:shared"/*/s2s/sessions";
641 for _, session in pairs(s2s_sessions) do
642 local remotehost, localhost, direction;
643 if session.direction == "outgoing" then
644 direction = "->";
645 count_out = count_out + 1;
646 remotehost, localhost = session.to_host or "?", session.from_host or "?";
647 else
648 direction = "<-";
649 count_in = count_in + 1;
650 remotehost, localhost = session.from_host or "?", session.to_host or "?";
652 local sess_lines = { l = localhost, r = remotehost,
653 annotate(session, { "", direction, remotehost or "?" })};
655 if (not match_jid) or remotehost:match(match_jid) or localhost:match(match_jid) then
656 table.insert(s2s_list, sess_lines);
657 -- luacheck: ignore 421/print
658 local print = function (s) table.insert(sess_lines, " "..s); end
659 if session.sendq then
660 print("There are "..#session.sendq.." queued outgoing stanzas for this connection");
662 if session.type == "s2sout_unauthed" then
663 if session.connecting then
664 print("Connection not yet established");
665 if not session.srv_hosts then
666 if not session.conn then
667 print("We do not yet have a DNS answer for this host's SRV records");
668 else
669 print("This host has no SRV records, using A record instead");
671 elseif session.srv_choice then
672 print("We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
673 local srv_choice = session.srv_hosts[session.srv_choice];
674 print("Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
676 elseif session.notopen then
677 print("The <stream> has not yet been opened");
678 elseif not session.dialback_key then
679 print("Dialback has not been initiated yet");
680 elseif session.dialback_key then
681 print("Dialback has been requested, but no result received");
684 if session.type == "s2sin_unauthed" then
685 print("Connection not yet authenticated");
686 elseif session.type == "s2sin" then
687 for name in pairs(session.hosts) do
688 if name ~= session.from_host then
689 print("also hosts "..tostring(name));
696 -- Sort by local host, then remote host
697 table.sort(s2s_list, function(a,b)
698 if a.l == b.l then return a.r < b.r; end
699 return a.l < b.l;
700 end);
701 local lasthost;
702 for _, sess_lines in ipairs(s2s_list) do
703 if sess_lines.l ~= lasthost then print(sess_lines.l); lasthost=sess_lines.l end
704 for _, line in ipairs(sess_lines) do print(line); end
706 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
709 function def_env.s2s:show_tls(match_jid)
710 return self:show(match_jid, tls_info);
713 local function print_subject(print, subject)
714 for _, entry in ipairs(subject) do
715 print(
716 (" %s: %q"):format(
717 entry.name or entry.oid,
718 entry.value:gsub("[\r\n%z%c]", " ")
724 -- As much as it pains me to use the 0-based depths that OpenSSL does,
725 -- I think there's going to be more confusion among operators if we
726 -- break from that.
727 local function print_errors(print, errors)
728 for depth, t in pairs(errors) do
729 print(
730 (" %d: %s"):format(
731 depth-1,
732 table.concat(t, "\n| ")
738 function def_env.s2s:showcert(domain)
739 local print = self.session.print;
740 local s2s_sessions = module:shared"/*/s2s/sessions";
741 local domain_sessions = set.new(array.collect(values(s2s_sessions)))
742 /function(session) return (session.to_host == domain or session.from_host == domain) and session or nil; end;
743 local cert_set = {};
744 for session in domain_sessions do
745 local conn = session.conn;
746 conn = conn and conn:socket();
747 if not conn.getpeerchain then
748 if conn.dohandshake then
749 error("This version of LuaSec does not support certificate viewing");
751 else
752 local cert = conn:getpeercertificate();
753 if cert then
754 local certs = conn:getpeerchain();
755 local digest = cert:digest("sha1");
756 if not cert_set[digest] then
757 local chain_valid, chain_errors = conn:getpeerverification();
758 cert_set[digest] = {
760 from = session.from_host,
761 to = session.to_host,
762 direction = session.direction
764 chain_valid = chain_valid;
765 chain_errors = chain_errors;
766 certs = certs;
768 else
769 table.insert(cert_set[digest], {
770 from = session.from_host,
771 to = session.to_host,
772 direction = session.direction
778 local domain_certs = array.collect(values(cert_set));
779 -- Phew. We now have a array of unique certificates presented by domain.
780 local n_certs = #domain_certs;
782 if n_certs == 0 then
783 return "No certificates found for "..domain;
786 local function _capitalize_and_colon(byte)
787 return string.upper(byte)..":";
789 local function pretty_fingerprint(hash)
790 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
793 for cert_info in values(domain_certs) do
794 local certs = cert_info.certs;
795 local cert = certs[1];
796 print("---")
797 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
798 print("");
799 local n_streams = #cert_info;
800 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
801 for _, stream in ipairs(cert_info) do
802 if stream.direction == "incoming" then
803 print(" "..stream.to.." <- "..stream.from);
804 else
805 print(" "..stream.from.." -> "..stream.to);
808 print("");
809 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
810 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
811 if chain_valid then
812 print("Trusted certificate: Yes");
813 else
814 print("Trusted certificate: No");
815 print_errors(print, errors);
817 print("");
818 print("Issuer: ");
819 print_subject(print, cert:issuer());
820 print("");
821 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
822 print("Subject:");
823 print_subject(print, cert:subject());
825 print("---");
826 return ("Showing "..n_certs.." certificate"
827 ..(n_certs==1 and "" or "s")
828 .." presented by "..domain..".");
831 function def_env.s2s:close(from, to)
832 local print, count = self.session.print, 0;
833 local s2s_sessions = module:shared"/*/s2s/sessions";
835 local match_id;
836 if from and not to then
837 match_id, from = from, nil;
838 elseif not to then
839 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
840 elseif from == to then
841 return false, "Both from and to are the same... you can't do that :)";
844 for _, session in pairs(s2s_sessions) do
845 local id = session.type..tostring(session):match("[a-f0-9]+$");
846 if (match_id and match_id == id)
847 or (session.from_host == from and session.to_host == to) then
848 print(("Closing connection from %s to %s [%s]"):format(session.from_host, session.to_host, id));
849 (session.close or s2smanager.destroy_session)(session);
850 count = count + 1 ;
853 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
856 function def_env.s2s:closeall(host)
857 local count = 0;
858 local s2s_sessions = module:shared"/*/s2s/sessions";
859 for _,session in pairs(s2s_sessions) do
860 if not host or session.from_host == host or session.to_host == host then
861 session:close();
862 count = count + 1;
865 if count == 0 then return false, "No sessions to close.";
866 else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
869 def_env.host = {}; def_env.hosts = def_env.host;
871 function def_env.host:activate(hostname, config)
872 return hostmanager.activate(hostname, config);
874 function def_env.host:deactivate(hostname, reason)
875 return hostmanager.deactivate(hostname, reason);
878 function def_env.host:list()
879 local print = self.session.print;
880 local i = 0;
881 local type;
882 for host, host_session in iterators.sorted_pairs(prosody.hosts) do
883 i = i + 1;
884 type = host_session.type;
885 if type == "local" then
886 print(host);
887 else
888 type = module:context(host):get_option_string("component_module", type);
889 if type ~= "component" then
890 type = type .. " component";
892 print(("%s (%s)"):format(host, type));
895 return true, i.." hosts";
898 def_env.port = {};
900 function def_env.port:list()
901 local print = self.session.print;
902 local services = portmanager.get_active_services().data;
903 local n_services, n_ports = 0, 0;
904 for service, interfaces in iterators.sorted_pairs(services) do
905 n_services = n_services + 1;
906 local ports_list = {};
907 for interface, ports in pairs(interfaces) do
908 for port in pairs(ports) do
909 table.insert(ports_list, "["..interface.."]:"..port);
912 n_ports = n_ports + #ports_list;
913 print(service..": "..table.concat(ports_list, ", "));
915 return true, n_services.." services listening on "..n_ports.." ports";
918 function def_env.port:close(close_port, close_interface)
919 close_port = assert(tonumber(close_port), "Invalid port number");
920 local n_closed = 0;
921 local services = portmanager.get_active_services().data;
922 for service, interfaces in pairs(services) do -- luacheck: ignore 213
923 for interface, ports in pairs(interfaces) do
924 if not close_interface or close_interface == interface then
925 if ports[close_port] then
926 self.session.print("Closing ["..interface.."]:"..close_port.."...");
927 local ok, err = portmanager.close(interface, close_port)
928 if not ok then
929 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
930 else
931 n_closed = n_closed + 1;
937 return true, "Closed "..n_closed.." ports";
940 def_env.muc = {};
942 local console_room_mt = {
943 __index = function (self, k) return self.room[k]; end;
944 __tostring = function (self)
945 return "MUC room <"..self.room.jid..">";
946 end;
949 local function check_muc(jid)
950 local room_name, host = jid_split(jid);
951 if not prosody.hosts[host] then
952 return nil, "No such host: "..host;
953 elseif not prosody.hosts[host].modules.muc then
954 return nil, "Host '"..host.."' is not a MUC service";
956 return room_name, host;
959 function def_env.muc:create(room_jid, config)
960 local room_name, host = check_muc(room_jid);
961 if not room_name then
962 return room_name, host;
964 if not room_name then return nil, host end
965 if config ~= nil and type(config) ~= "table" then return nil, "Config must be a table"; end
966 if prosody.hosts[host].modules.muc.get_room_from_jid(room_jid) then return nil, "Room exists already" end
967 return prosody.hosts[host].modules.muc.create_room(room_jid, config);
970 function def_env.muc:room(room_jid)
971 local room_name, host = check_muc(room_jid);
972 if not room_name then
973 return room_name, host;
975 local room_obj = prosody.hosts[host].modules.muc.get_room_from_jid(room_jid);
976 if not room_obj then
977 return nil, "No such room: "..room_jid;
979 return setmetatable({ room = room_obj }, console_room_mt);
982 function def_env.muc:list(host)
983 local host_session = prosody.hosts[host];
984 if not host_session or not host_session.modules.muc then
985 return nil, "Please supply the address of a local MUC component";
987 local print = self.session.print;
988 local c = 0;
989 for room in host_session.modules.muc.each_room() do
990 print(room.jid);
991 c = c + 1;
993 return true, c.." rooms";
996 local um = require"core.usermanager";
998 def_env.user = {};
999 function def_env.user:create(jid, password)
1000 local username, host = jid_split(jid);
1001 if not prosody.hosts[host] then
1002 return nil, "No such host: "..host;
1003 elseif um.user_exists(username, host) then
1004 return nil, "User exists";
1006 local ok, err = um.create_user(username, password, host);
1007 if ok then
1008 return true, "User created";
1009 else
1010 return nil, "Could not create user: "..err;
1014 function def_env.user:delete(jid)
1015 local username, host = jid_split(jid);
1016 if not prosody.hosts[host] then
1017 return nil, "No such host: "..host;
1018 elseif not um.user_exists(username, host) then
1019 return nil, "No such user";
1021 local ok, err = um.delete_user(username, host);
1022 if ok then
1023 return true, "User deleted";
1024 else
1025 return nil, "Could not delete user: "..err;
1029 function def_env.user:password(jid, password)
1030 local username, host = jid_split(jid);
1031 if not prosody.hosts[host] then
1032 return nil, "No such host: "..host;
1033 elseif not um.user_exists(username, host) then
1034 return nil, "No such user";
1036 local ok, err = um.set_password(username, password, host, nil);
1037 if ok then
1038 return true, "User password changed";
1039 else
1040 return nil, "Could not change password for user: "..err;
1044 function def_env.user:list(host, pat)
1045 if not host then
1046 return nil, "No host given";
1047 elseif not prosody.hosts[host] then
1048 return nil, "No such host";
1050 local print = self.session.print;
1051 local total, matches = 0, 0;
1052 for user in um.users(host) do
1053 if not pat or user:match(pat) then
1054 print(user.."@"..host);
1055 matches = matches + 1;
1057 total = total + 1;
1059 return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
1062 def_env.xmpp = {};
1064 local st = require "util.stanza";
1065 function def_env.xmpp:ping(localhost, remotehost)
1066 if prosody.hosts[localhost] then
1067 module:send(st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
1068 :tag("ping", {xmlns="urn:xmpp:ping"}), prosody.hosts[localhost]);
1069 return true, "Sent ping";
1070 else
1071 return nil, "No such host";
1075 def_env.dns = {};
1076 local adns = require"net.adns";
1077 local dns = require"net.dns";
1079 function def_env.dns:lookup(name, typ, class)
1080 local ret = "Query sent";
1081 local print = self.session.print;
1082 local function handler(...)
1083 ret = "Got response";
1084 print(...);
1086 adns.lookup(handler, name, typ, class);
1087 return true, ret;
1090 function def_env.dns:addnameserver(...)
1091 dns._resolver:addnameserver(...)
1092 return true
1095 function def_env.dns:setnameserver(...)
1096 dns._resolver:setnameserver(...)
1097 return true
1100 function def_env.dns:purge()
1101 dns.purge()
1102 return true
1105 function def_env.dns:cache()
1106 return true, "Cache:\n"..tostring(dns.cache())
1109 def_env.http = {};
1111 function def_env.http:list()
1112 local print = self.session.print;
1114 for host in pairs(prosody.hosts) do
1115 local http_apps = modulemanager.get_items("http-provider", host);
1116 if #http_apps > 0 then
1117 local http_host = module:context(host):get_option_string("http_host");
1118 print("HTTP endpoints on "..host..(http_host and (" (using "..http_host.."):") or ":"));
1119 for _, provider in ipairs(http_apps) do
1120 local url = module:context(host):http_url(provider.name, provider.default_path);
1121 print("", url);
1123 print("");
1127 local default_host = module:get_option_string("http_default_host");
1128 if not default_host then
1129 print("HTTP requests to unknown hosts will return 404 Not Found");
1130 else
1131 print("HTTP requests to unknown hosts will be handled by "..default_host);
1133 return true;
1136 def_env.debug = {};
1138 function def_env.debug:logevents(host)
1139 helpers.log_host_events(host);
1140 return true;
1143 function def_env.debug:events(host, event)
1144 local events_obj;
1145 if host and host ~= "*" then
1146 if host == "http" then
1147 events_obj = require "net.http.server"._events;
1148 elseif not prosody.hosts[host] then
1149 return false, "Unknown host: "..host;
1150 else
1151 events_obj = prosody.hosts[host].events;
1153 else
1154 events_obj = prosody.events;
1156 return true, helpers.show_events(events_obj, event);
1159 function def_env.debug:timers()
1160 local socket = require "socket";
1161 local print = self.session.print;
1162 local add_task = require"util.timer".add_task;
1163 local h, params = add_task.h, add_task.params;
1164 if h then
1165 print("-- util.timer");
1166 for i, id in ipairs(h.ids) do
1167 if not params[id] then
1168 print(os.date("%F %T", h.priorities[i]), h.items[id]);
1169 elseif not params[id].callback then
1170 print(os.date("%F %T", h.priorities[i]), h.items[id], unpack(params[id]));
1171 else
1172 print(os.date("%F %T", h.priorities[i]), params[id].callback, unpack(params[id]));
1176 if server.event_base then
1177 local count = 0;
1178 for _, v in pairs(debug.getregistry()) do
1179 if type(v) == "function" and v.callback and v.callback == add_task._on_timer then
1180 count = count + 1;
1183 print(count .. " libevent callbacks");
1185 if h then
1186 local next_time = h:peek();
1187 if next_time then
1188 return true, os.date("Next event at %F %T (in %%.6fs)", next_time):format(next_time - socket.gettime());
1191 return true;
1194 -- COMPAT: debug:timers() was timer:info() for some time in trunk
1195 def_env.timer = { info = def_env.debug.timers };
1197 module:hook("server-stopping", function(event)
1198 for _, session in pairs(sessions) do
1199 session.print("Shutting down: "..(event.reason or "unknown reason"));
1201 end);
1203 def_env.stats = {};
1205 local function format_stat(type, value, ref_value)
1206 ref_value = ref_value or value;
1207 --do return tostring(value) end
1208 if type == "duration" then
1209 if ref_value < 0.001 then
1210 return ("%d µs"):format(value*1000000);
1211 elseif ref_value < 0.9 then
1212 return ("%0.2f ms"):format(value*1000);
1214 return ("%0.2f"):format(value);
1215 elseif type == "size" then
1216 if ref_value > 1048576 then
1217 return ("%d MB"):format(value/1048576);
1218 elseif ref_value > 1024 then
1219 return ("%d KB"):format(value/1024);
1221 return ("%d bytes"):format(value);
1222 elseif type == "rate" then
1223 if ref_value < 0.9 then
1224 return ("%0.2f/min"):format(value*60);
1226 return ("%0.2f/sec"):format(value);
1228 return tostring(value);
1231 local stats_methods = {};
1232 function stats_methods:bounds(_lower, _upper)
1233 for _, stat_info in ipairs(self) do
1234 local data = stat_info[4];
1235 if data then
1236 local lower = _lower or data.min;
1237 local upper = _upper or data.max;
1238 local new_data = {
1239 min = lower;
1240 max = upper;
1241 samples = {};
1242 sample_count = 0;
1243 count = data.count;
1244 units = data.units;
1246 local sum = 0;
1247 for _, v in ipairs(data.samples) do
1248 if v > upper then
1249 break;
1250 elseif v>=lower then
1251 table.insert(new_data.samples, v);
1252 sum = sum + v;
1255 new_data.sample_count = #new_data.samples;
1256 stat_info[4] = new_data;
1257 stat_info[3] = sum/new_data.sample_count;
1260 return self;
1263 function stats_methods:trim(lower, upper)
1264 upper = upper or (100-lower);
1265 local statistics = require "util.statistics";
1266 for _, stat_info in ipairs(self) do
1267 -- Strip outliers
1268 local data = stat_info[4];
1269 if data then
1270 local new_data = {
1271 min = statistics.get_percentile(data, lower);
1272 max = statistics.get_percentile(data, upper);
1273 samples = {};
1274 sample_count = 0;
1275 count = data.count;
1276 units = data.units;
1278 local sum = 0;
1279 for _, v in ipairs(data.samples) do
1280 if v > new_data.max then
1281 break;
1282 elseif v>=new_data.min then
1283 table.insert(new_data.samples, v);
1284 sum = sum + v;
1287 new_data.sample_count = #new_data.samples;
1288 stat_info[4] = new_data;
1289 stat_info[3] = sum/new_data.sample_count;
1292 return self;
1295 function stats_methods:max(upper)
1296 return self:bounds(nil, upper);
1299 function stats_methods:min(lower)
1300 return self:bounds(lower, nil);
1303 function stats_methods:summary()
1304 local statistics = require "util.statistics";
1305 for _, stat_info in ipairs(self) do
1306 local type, value, data = stat_info[2], stat_info[3], stat_info[4];
1307 if data and data.samples then
1308 table.insert(stat_info.output, string.format("Count: %d (%d captured)",
1309 data.count,
1310 data.sample_count
1312 table.insert(stat_info.output, string.format("Min: %s Mean: %s Max: %s",
1313 format_stat(type, data.min),
1314 format_stat(type, value),
1315 format_stat(type, data.max)
1317 table.insert(stat_info.output, string.format("Q1: %s Median: %s Q3: %s",
1318 format_stat(type, statistics.get_percentile(data, 25)),
1319 format_stat(type, statistics.get_percentile(data, 50)),
1320 format_stat(type, statistics.get_percentile(data, 75))
1324 return self;
1327 function stats_methods:cfgraph()
1328 for _, stat_info in ipairs(self) do
1329 local name, type, value, data = unpack(stat_info, 1, 4);
1330 local function print(s)
1331 table.insert(stat_info.output, s);
1334 if data and data.sample_count and data.sample_count > 0 then
1335 local raw_histogram = require "util.statistics".get_histogram(data);
1337 local graph_width, graph_height = 50, 10;
1338 local eighth_chars = " ▁▂▃▄▅▆▇█";
1340 local range = data.max - data.min;
1342 if range > 0 then
1343 local x_scaling = #raw_histogram/graph_width;
1344 local histogram = {};
1345 for i = 1, graph_width do
1346 histogram[i] = math.max(raw_histogram[i*x_scaling-1] or 0, raw_histogram[i*x_scaling] or 0);
1349 print("");
1350 print(("_"):rep(52)..format_stat(type, data.max));
1351 for row = graph_height, 1, -1 do
1352 local row_chars = {};
1353 local min_eighths, max_eighths = 8, 0;
1354 for i = 1, #histogram do
1355 local char_eighths = math.ceil(math.max(math.min((graph_height/(data.max/histogram[i]))-(row-1), 1), 0)*8);
1356 if char_eighths < min_eighths then
1357 min_eighths = char_eighths;
1359 if char_eighths > max_eighths then
1360 max_eighths = char_eighths;
1362 if char_eighths == 0 then
1363 row_chars[i] = "-";
1364 else
1365 local char = eighth_chars:sub(char_eighths*3+1, char_eighths*3+3);
1366 row_chars[i] = char;
1369 print(table.concat(row_chars).."|-"..format_stat(type, data.max/(graph_height/(row-0.5))));
1371 print(("\\ "):rep(11));
1372 local x_labels = {};
1373 for i = 1, 11 do
1374 local s = ("%-4s"):format((i-1)*10);
1375 if #s > 4 then
1376 s = s:sub(1, 3).."…";
1378 x_labels[i] = s;
1380 print(" "..table.concat(x_labels, " "));
1381 local units = "%";
1382 local margin = math.floor((graph_width-#units)/2);
1383 print((" "):rep(margin)..units);
1384 else
1385 print("[range too small to graph]");
1387 print("");
1390 return self;
1393 function stats_methods:histogram()
1394 for _, stat_info in ipairs(self) do
1395 local name, type, value, data = unpack(stat_info, 1, 4);
1396 local function print(s)
1397 table.insert(stat_info.output, s);
1400 if not data then
1401 print("[no data]");
1402 return self;
1403 elseif not data.sample_count then
1404 print("[not a sampled metric type]");
1405 return self;
1408 local graph_width, graph_height = 50, 10;
1409 local eighth_chars = " ▁▂▃▄▅▆▇█";
1411 local range = data.max - data.min;
1413 if range > 0 then
1414 local n_buckets = graph_width;
1416 local histogram = {};
1417 for i = 1, n_buckets do
1418 histogram[i] = 0;
1420 local max_bin_samples = 0;
1421 for _, d in ipairs(data.samples) do
1422 local bucket = math.floor(1+(n_buckets-1)/(range/(d-data.min)));
1423 histogram[bucket] = histogram[bucket] + 1;
1424 if histogram[bucket] > max_bin_samples then
1425 max_bin_samples = histogram[bucket];
1429 print("");
1430 print(("_"):rep(52)..max_bin_samples);
1431 for row = graph_height, 1, -1 do
1432 local row_chars = {};
1433 local min_eighths, max_eighths = 8, 0;
1434 for i = 1, #histogram do
1435 local char_eighths = math.ceil(math.max(math.min((graph_height/(max_bin_samples/histogram[i]))-(row-1), 1), 0)*8);
1436 if char_eighths < min_eighths then
1437 min_eighths = char_eighths;
1439 if char_eighths > max_eighths then
1440 max_eighths = char_eighths;
1442 if char_eighths == 0 then
1443 row_chars[i] = "-";
1444 else
1445 local char = eighth_chars:sub(char_eighths*3+1, char_eighths*3+3);
1446 row_chars[i] = char;
1449 print(table.concat(row_chars).."|-"..math.ceil((max_bin_samples/graph_height)*(row-0.5)));
1451 print(("\\ "):rep(11));
1452 local x_labels = {};
1453 for i = 1, 11 do
1454 local s = ("%-4s"):format(format_stat(type, data.min+range*i/11, data.min):match("^%S+"));
1455 if #s > 4 then
1456 s = s:sub(1, 3).."…";
1458 x_labels[i] = s;
1460 print(" "..table.concat(x_labels, " "));
1461 local units = format_stat(type, data.min):match("%s+(.+)$") or data.units or "";
1462 local margin = math.floor((graph_width-#units)/2);
1463 print((" "):rep(margin)..units);
1464 else
1465 print("[range too small to graph]");
1467 print("");
1469 return self;
1472 local function stats_tostring(stats)
1473 local print = stats.session.print;
1474 for _, stat_info in ipairs(stats) do
1475 if #stat_info.output > 0 then
1476 print("\n#"..stat_info[1]);
1477 print("");
1478 for _, v in ipairs(stat_info.output) do
1479 print(v);
1481 print("");
1482 else
1483 print(("%-50s %s"):format(stat_info[1], format_stat(stat_info[2], stat_info[3])));
1486 return #stats.." statistics displayed";
1489 local stats_mt = {__index = stats_methods, __tostring = stats_tostring }
1490 local function new_stats_context(self)
1491 return setmetatable({ session = self.session, stats = true }, stats_mt);
1494 function def_env.stats:show(filter)
1495 local stats, changed, extra = require "core.statsmanager".get_stats();
1496 local available, displayed = 0, 0;
1497 local displayed_stats = new_stats_context(self);
1498 for name, value in pairs(stats) do
1499 available = available + 1;
1500 if not filter or name:match(filter) then
1501 displayed = displayed + 1;
1502 local type = name:match(":(%a+)$");
1503 table.insert(displayed_stats, {
1504 name, type, value, extra[name];
1505 output = {};
1509 return displayed_stats;
1514 -------------
1516 function printbanner(session)
1517 local option = module:get_option_string("console_banner", "full");
1518 if option == "full" or option == "graphic" then
1519 session.print [[
1520 ____ \ / _
1521 | _ \ _ __ ___ ___ _-_ __| |_ _
1522 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1523 | __/| | | (_) \__ \ |_| | (_| | |_| |
1524 |_| |_| \___/|___/\___/ \__,_|\__, |
1525 A study in simplicity |___/
1529 if option == "short" or option == "full" then
1530 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1531 session.print("You may find more help on using this console in our online documentation at ");
1532 session.print("https://prosody.im/doc/console\n");
1534 if option ~= "short" and option ~= "full" and option ~= "graphic" then
1535 session.print(option);
1539 module:provides("net", {
1540 name = "console";
1541 listener = console_listener;
1542 default_port = 5582;
1543 private = true;