Comparison

plugins/mod_admin_telnet.lua @ 10857:826023c3322b

mod_admin_telnet: Become a front for mod_admin_shell
author Matthew Wild <mwild1@gmail.com>
date Mon, 01 Jun 2020 15:43:47 +0100
parent 10845:785fa0112411
child 10859:8de0057b4279
comparison
equal deleted inserted replaced
10856:c99711eda0d1 10857:826023c3322b
6 -- COPYING file in the source package for more information. 6 -- COPYING file in the source package for more information.
7 -- 7 --
8 -- luacheck: ignore 212/self 8 -- luacheck: ignore 212/self
9 9
10 module:set_global(); 10 module:set_global();
11 11 module:depends("admin_shell");
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";
18
19 local _G = _G;
20
21 local prosody = _G.prosody;
22 12
23 local console_listener = { default_port = 5582; default_mode = "*a"; interface = "127.0.0.1" }; 13 local console_listener = { default_port = 5582; default_mode = "*a"; interface = "127.0.0.1" };
24 14
25 local unpack = table.unpack or unpack; -- luacheck: ignore 113
26 local iterators = require "util.iterators";
27 local keys, values = iterators.keys, iterators.values;
28 local jid_bare, jid_split, jid_join = import("util.jid", "bare", "prepped_split", "join");
29 local set, array = require "util.set", require "util.array";
30 local cert_verify_identity = require "util.x509".verify_identity;
31 local envload = require "util.envload".envload;
32 local envloadfile = require "util.envload".envloadfile;
33 local has_pposix, pposix = pcall(require, "util.pposix");
34 local async = require "util.async"; 15 local async = require "util.async";
35 local serialization = require "util.serialization"; 16 local st = require "util.stanza";
36 local serialize_config = serialization.new ({ fatal = false, unquoted = true});
37 local time = require "util.time";
38 17
39 local commands = module:shared("commands") 18 local def_env = module:shared("admin_shell/env");
40 local def_env = module:shared("env");
41 local default_env_mt = { __index = def_env }; 19 local default_env_mt = { __index = def_env };
42 20
43 local function redirect_output(target, session) 21 local function printbanner(session)
44 local env = setmetatable({ print = session.print }, { __index = function (_, k) return rawget(target, k); end }); 22 local option = module:get_option_string("console_banner", "full");
45 env.dofile = function(name) 23 if option == "full" or option == "graphic" then
46 local f, err = envloadfile(name, env); 24 session.print [[
47 if not f then return f, err; end 25 ____ \ / _
48 return f(); 26 | _ \ _ __ ___ ___ _-_ __| |_ _
49 end; 27 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
50 return env; 28 | __/| | | (_) \__ \ |_| | (_| | |_| |
29 |_| |_| \___/|___/\___/ \__,_|\__, |
30 A study in simplicity |___/
31
32 ]]
33 end
34 if option == "short" or option == "full" then
35 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
36 session.print("You may find more help on using this console in our online documentation at ");
37 session.print("https://prosody.im/doc/console\n");
38 end
39 if option ~= "short" and option ~= "full" and option ~= "graphic" then
40 session.print(option);
41 end
51 end 42 end
52 43
53 console = {}; 44 console = {};
54 45
55 local runner_callbacks = {}; 46 local runner_callbacks = {};
71 62
72 63
73 function console:new_session(conn) 64 function console:new_session(conn)
74 local w = function(s) conn:write(s:gsub("\n", "\r\n")); end; 65 local w = function(s) conn:write(s:gsub("\n", "\r\n")); end;
75 local session = { conn = conn; 66 local session = { conn = conn;
76 send = function (t) w(tostring(t)); end; 67 send = function (t)
68 if st.is_stanza(t) and t.name == "repl-result" then
69 t = "| "..t:get_text().."\n";
70 end
71 w(tostring(t));
72 end;
77 print = function (...) 73 print = function (...)
78 local t = {}; 74 local t = {};
79 for i=1,select("#", ...) do 75 for i=1,select("#", ...) do
80 t[i] = tostring(select(i, ...)); 76 t[i] = tostring(select(i, ...));
81 end 77 end
102 98
103 return session; 99 return session;
104 end 100 end
105 101
106 function console:process_line(session, line) 102 function console:process_line(session, line)
107 local useglobalenv; 103 line = line:gsub("\r?\n$", "");
108 104 if line == "bye" or line == "quit" or line == "exit" or line:byte() == 4 then
109 if line:match("^>") then 105 session.print("See you!");
110 line = line:gsub("^>", ""); 106 session:disconnect();
111 useglobalenv = true;
112 elseif line == "\004" then
113 commands["bye"](session, line);
114 return;
115 else
116 local command = line:match("^%w+") or line:match("%p");
117 if commands[command] then
118 commands[command](session, line);
119 return;
120 end
121 end
122
123 session.env._ = line;
124
125 if not useglobalenv and commands[line:lower()] then
126 commands[line:lower()](session, line);
127 return; 107 return;
128 end 108 end
129 109 return module:fire_event("admin/repl-line", { origin = session, stanza = st.stanza("repl"):text(line) });
130 local chunkname = "=console";
131 local env = (useglobalenv and redirect_output(_G, session)) or session.env or nil
132 -- luacheck: ignore 311/err
133 local chunk, err = envload("return "..line, chunkname, env);
134 if not chunk then
135 chunk, err = envload(line, chunkname, env);
136 if not chunk then
137 err = err:gsub("^%[string .-%]:%d+: ", "");
138 err = err:gsub("^:%d+: ", "");
139 err = err:gsub("'<eof>'", "the end of the line");
140 session.print("Sorry, I couldn't understand that... "..err);
141 return;
142 end
143 end
144
145 local taskok, message = chunk();
146
147 if not message then
148 if type(taskok) ~= "string" and useglobalenv then
149 taskok = session.serialize(taskok);
150 end
151 session.print("Result: "..tostring(taskok));
152 return;
153 elseif (not taskok) and message then
154 session.print("Command completed with a problem");
155 session.print("Message: "..tostring(message));
156 return;
157 end
158
159 session.print("OK: "..tostring(message));
160 end 110 end
161 111
162 local sessions = {}; 112 local sessions = {};
163 113
164 function module.save() 114 function module.save()
216 166
217 function console_listener.ondetach(conn) 167 function console_listener.ondetach(conn)
218 sessions[conn] = nil; 168 sessions[conn] = nil;
219 end 169 end
220 170
221 -- Console commands --
222 -- These are simple commands, not valid standalone in Lua
223
224 function commands.bye(session)
225 session.print("See you! :)");
226 session.closed = true;
227 session.disconnect();
228 end
229 commands.quit, commands.exit = commands.bye, commands.bye;
230
231 commands["!"] = function (session, data)
232 if data:match("^!!") and session.env._ then
233 session.print("!> "..session.env._);
234 return console_listener.onincoming(session.conn, session.env._);
235 end
236 local old, new = data:match("^!(.-[^\\])!(.-)!$");
237 if old and new then
238 local ok, res = pcall(string.gsub, session.env._, old, new);
239 if not ok then
240 session.print(res)
241 return;
242 end
243 session.print("!> "..res);
244 return console_listener.onincoming(session.conn, res);
245 end
246 session.print("Sorry, not sure what you want");
247 end
248
249
250 function commands.help(session, data)
251 local print = session.print;
252 local section = data:match("^help (%w+)");
253 if not section then
254 print [[Commands are divided into multiple sections. For help on a particular section, ]]
255 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
256 print [[]]
257 print [[c2s - Commands to manage local client-to-server sessions]]
258 print [[s2s - Commands to manage sessions between this server and others]]
259 print [[http - Commands to inspect HTTP services]] -- XXX plural but there is only one so far
260 print [[module - Commands to load/reload/unload modules/plugins]]
261 print [[host - Commands to activate, deactivate and list virtual hosts]]
262 print [[user - Commands to create and delete users, and change their passwords]]
263 print [[server - Uptime, version, shutting down, etc.]]
264 print [[port - Commands to manage ports the server is listening on]]
265 print [[dns - Commands to manage and inspect the internal DNS resolver]]
266 print [[xmpp - Commands for sending XMPP stanzas]]
267 print [[debug - Commands for debugging the server]]
268 print [[config - Reloading the configuration, etc.]]
269 print [[console - Help regarding the console itself]]
270 elseif section == "c2s" then
271 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
272 print [[c2s:show_insecure() - Show all unencrypted client connections]]
273 print [[c2s:show_secure() - Show all encrypted client connections]]
274 print [[c2s:show_tls() - Show TLS cipher info for encrypted sessions]]
275 print [[c2s:count() - Count sessions without listing them]]
276 print [[c2s:close(jid) - Close all sessions for the specified JID]]
277 print [[c2s:closeall() - Close all active c2s connections ]]
278 elseif section == "s2s" then
279 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
280 print [[s2s:show_tls(domain) - Show TLS cipher info for encrypted sessions]]
281 print [[s2s:close(from, to) - Close a connection from one domain to another]]
282 print [[s2s:closeall(host) - Close all the incoming/outgoing s2s sessions to specified host]]
283 elseif section == "http" then
284 print [[http:list(hosts) - Show HTTP endpoints]]
285 elseif section == "module" then
286 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
287 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
288 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
289 print [[module:list(host) - List the modules loaded on the specified host]]
290 elseif section == "host" then
291 print [[host:activate(hostname) - Activates the specified host]]
292 print [[host:deactivate(hostname) - Disconnects all clients on this host and deactivates]]
293 print [[host:list() - List the currently-activated hosts]]
294 elseif section == "user" then
295 print [[user:create(jid, password) - Create the specified user account]]
296 print [[user:password(jid, password) - Set the password for the specified user account]]
297 print [[user:delete(jid) - Permanently remove the specified user account]]
298 print [[user:list(hostname, pattern) - List users on the specified host, optionally filtering with a pattern]]
299 elseif section == "server" then
300 print [[server:version() - Show the server's version number]]
301 print [[server:uptime() - Show how long the server has been running]]
302 print [[server:memory() - Show details about the server's memory usage]]
303 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
304 elseif section == "port" then
305 print [[port:list() - Lists all network ports prosody currently listens on]]
306 print [[port:close(port, interface) - Close a port]]
307 elseif section == "dns" then
308 print [[dns:lookup(name, type, class) - Do a DNS lookup]]
309 print [[dns:addnameserver(nameserver) - Add a nameserver to the list]]
310 print [[dns:setnameserver(nameserver) - Replace the list of name servers with the supplied one]]
311 print [[dns:purge() - Clear the DNS cache]]
312 print [[dns:cache() - Show cached records]]
313 elseif section == "xmpp" then
314 print [[xmpp:ping(localhost, remotehost) -- Sends a ping to a remote XMPP server and reports the response]]
315 elseif section == "config" then
316 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
317 print [[config:get([host,] option) - Show the value of a config option.]]
318 elseif section == "stats" then -- luacheck: ignore 542
319 -- TODO describe how stats:show() works
320 elseif section == "debug" then
321 print [[debug:logevents(host) - Enable logging of fired events on host]]
322 print [[debug:events(host, event) - Show registered event handlers]]
323 print [[debug:timers() - Show information about scheduled timers]]
324 elseif section == "console" then
325 print [[Hey! Welcome to Prosody's admin console.]]
326 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
327 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
328 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
329 print [[]]
330 print [[For now we offer a couple of handy shortcuts:]]
331 print [[!! - Repeat the last command]]
332 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
333 print [[]]
334 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
335 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
336 print [[the running server. Great fun, but be careful not to break anything :)]]
337 end
338 print [[]]
339 end
340
341 -- Session environment --
342 -- Anything in def_env will be accessible within the session as a global variable
343
344 --luacheck: ignore 212/self
345 local serialize_defaults = module:get_option("console_prettyprint_settings", { fatal = false, unquoted = true, maxdepth = 2})
346
347 def_env.output = {};
348 function def_env.output:configure(opts)
349 if type(opts) ~= "table" then
350 opts = { preset = opts };
351 end
352 if not opts.fallback then
353 -- XXX Error message passed to fallback is lost, does it matter?
354 opts.fallback = tostring;
355 end
356 for k,v in pairs(serialize_defaults) do
357 if opts[k] == nil then
358 opts[k] = v;
359 end
360 end
361 self.session.serialize = serialization.new(opts);
362 end
363
364 def_env.server = {};
365
366 function def_env.server:insane_reload()
367 prosody.unlock_globals();
368 dofile "prosody"
369 prosody = _G.prosody;
370 return true, "Server reloaded";
371 end
372
373 function def_env.server:version()
374 return true, tostring(prosody.version or "unknown");
375 end
376
377 function def_env.server:uptime()
378 local t = os.time()-prosody.start_time;
379 local seconds = t%60;
380 t = (t - seconds)/60;
381 local minutes = t%60;
382 t = (t - minutes)/60;
383 local hours = t%24;
384 t = (t - hours)/24;
385 local days = t;
386 return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
387 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
388 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
389 end
390
391 function def_env.server:shutdown(reason)
392 prosody.shutdown(reason);
393 return true, "Shutdown initiated";
394 end
395
396 local function human(kb)
397 local unit = "K";
398 if kb > 1024 then
399 kb, unit = kb/1024, "M";
400 end
401 return ("%0.2f%sB"):format(kb, unit);
402 end
403
404 function def_env.server:memory()
405 if not has_pposix or not pposix.meminfo then
406 return true, "Lua is using "..human(collectgarbage("count"));
407 end
408 local mem, lua_mem = pposix.meminfo(), collectgarbage("count");
409 local print = self.session.print;
410 print("Process: "..human((mem.allocated+mem.allocated_mmap)/1024));
411 print(" Used: "..human(mem.used/1024).." ("..human(lua_mem).." by Lua)");
412 print(" Free: "..human(mem.unused/1024).." ("..human(mem.returnable/1024).." returnable)");
413 return true, "OK";
414 end
415
416 def_env.module = {};
417
418 local function get_hosts_set(hosts)
419 if type(hosts) == "table" then
420 if hosts[1] then
421 return set.new(hosts);
422 elseif hosts._items then
423 return hosts;
424 end
425 elseif type(hosts) == "string" then
426 return set.new { hosts };
427 elseif hosts == nil then
428 return set.new(array.collect(keys(prosody.hosts)));
429 end
430 end
431
432 -- Hosts with a module or all virtualhosts if no module given
433 -- matching modules_enabled in the global section
434 local function get_hosts_with_module(hosts, module)
435 local hosts_set = get_hosts_set(hosts)
436 / function (host)
437 if module then
438 -- Module given, filter in hosts with this module loaded
439 if modulemanager.is_loaded(host, module) then
440 return host;
441 else
442 return nil;
443 end
444 end
445 if not hosts then
446 -- No hosts given, filter in VirtualHosts
447 if prosody.hosts[host].type == "local" then
448 return host;
449 else
450 return nil
451 end
452 end;
453 -- No module given, but hosts are, don't filter at all
454 return host;
455 end;
456 if module and modulemanager.get_module("*", module) then
457 hosts_set:add("*");
458 end
459 return hosts_set;
460 end
461
462 function def_env.module:load(name, hosts, config)
463 hosts = get_hosts_with_module(hosts);
464
465 -- Load the module for each host
466 local ok, err, count, mod = true, nil, 0;
467 for host in hosts do
468 if (not modulemanager.is_loaded(host, name)) then
469 mod, err = modulemanager.load(host, name, config);
470 if not mod then
471 ok = false;
472 if err == "global-module-already-loaded" then
473 if count > 0 then
474 ok, err, count = true, nil, 1;
475 end
476 break;
477 end
478 self.session.print(err or "Unknown error loading module");
479 else
480 count = count + 1;
481 self.session.print("Loaded for "..mod.module.host);
482 end
483 end
484 end
485
486 return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
487 end
488
489 function def_env.module:unload(name, hosts)
490 hosts = get_hosts_with_module(hosts, name);
491
492 -- Unload the module for each host
493 local ok, err, count = true, nil, 0;
494 for host in hosts do
495 if modulemanager.is_loaded(host, name) then
496 ok, err = modulemanager.unload(host, name);
497 if not ok then
498 ok = false;
499 self.session.print(err or "Unknown error unloading module");
500 else
501 count = count + 1;
502 self.session.print("Unloaded from "..host);
503 end
504 end
505 end
506 return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
507 end
508
509 local function _sort_hosts(a, b)
510 if a == "*" then return true
511 elseif b == "*" then return false
512 else return a:gsub("[^.]+", string.reverse):reverse() < b:gsub("[^.]+", string.reverse):reverse(); end
513 end
514
515 function def_env.module:reload(name, hosts)
516 hosts = array.collect(get_hosts_with_module(hosts, name)):sort(_sort_hosts)
517
518 -- Reload the module for each host
519 local ok, err, count = true, nil, 0;
520 for _, host in ipairs(hosts) do
521 if modulemanager.is_loaded(host, name) then
522 ok, err = modulemanager.reload(host, name);
523 if not ok then
524 ok = false;
525 self.session.print(err or "Unknown error reloading module");
526 else
527 count = count + 1;
528 if ok == nil then
529 ok = true;
530 end
531 self.session.print("Reloaded on "..host);
532 end
533 end
534 end
535 return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
536 end
537
538 function def_env.module:list(hosts)
539 hosts = array.collect(set.new({ not hosts and "*" or nil }) + get_hosts_set(hosts)):sort(_sort_hosts);
540
541 local print = self.session.print;
542 for _, host in ipairs(hosts) do
543 print((host == "*" and "Global" or host)..":");
544 local modules = array.collect(keys(modulemanager.get_modules(host) or {})):sort();
545 if #modules == 0 then
546 if prosody.hosts[host] then
547 print(" No modules loaded");
548 else
549 print(" Host not found");
550 end
551 else
552 for _, name in ipairs(modules) do
553 local status, status_text = modulemanager.get_module(host, name).module:get_status();
554 local status_summary = "";
555 if status == "warn" or status == "error" then
556 status_summary = (" (%s: %s)"):format(status, status_text);
557 end
558 print((" %s%s"):format(name, status_summary));
559 end
560 end
561 end
562 end
563
564 def_env.config = {};
565 function def_env.config:load(filename, format)
566 local config_load = require "core.configmanager".load;
567 local ok, err = config_load(filename, format);
568 if not ok then
569 return false, err or "Unknown error loading config";
570 end
571 return true, "Config loaded";
572 end
573
574 function def_env.config:get(host, key)
575 if key == nil then
576 host, key = "*", host;
577 end
578 local config_get = require "core.configmanager".get
579 return true, serialize_config(config_get(host, key));
580 end
581
582 function def_env.config:reload()
583 local ok, err = prosody.reload_config();
584 return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
585 end
586
587 local function common_info(session, line)
588 if session.id then
589 line[#line+1] = "["..session.id.."]"
590 else
591 line[#line+1] = "["..session.type..(tostring(session):match("%x*$")).."]"
592 end
593 end
594
595 local function session_flags(session, line)
596 line = line or {};
597 common_info(session, line);
598 if session.type == "c2s" then
599 local status, priority = "unavailable", tostring(session.priority or "-");
600 if session.presence then
601 status = session.presence:get_child_text("show") or "available";
602 end
603 line[#line+1] = status.."("..priority..")";
604 end
605 if session.cert_identity_status == "valid" then
606 line[#line+1] = "(authenticated)";
607 end
608 if session.dialback_key then
609 line[#line+1] = "(dialback)";
610 end
611 if session.external_auth then
612 line[#line+1] = "(SASL)";
613 end
614 if session.secure then
615 line[#line+1] = "(encrypted)";
616 end
617 if session.compressed then
618 line[#line+1] = "(compressed)";
619 end
620 if session.smacks then
621 line[#line+1] = "(sm)";
622 end
623 if session.ip and session.ip:match(":") then
624 line[#line+1] = "(IPv6)";
625 end
626 if session.remote then
627 line[#line+1] = "(remote)";
628 end
629 if session.incoming and session.outgoing then
630 line[#line+1] = "(bidi)";
631 elseif session.is_bidi or session.bidi_session then
632 line[#line+1] = "(bidi)";
633 end
634 if session.bosh_version then
635 line[#line+1] = "(bosh)";
636 end
637 if session.websocket_request then
638 line[#line+1] = "(websocket)";
639 end
640 return table.concat(line, " ");
641 end
642
643 local function tls_info(session, line)
644 line = line or {};
645 common_info(session, line);
646 if session.secure then
647 local sock = session.conn and session.conn.socket and session.conn:socket();
648 if sock then
649 local info = sock.info and sock:info();
650 if info then
651 line[#line+1] = ("(%s with %s)"):format(info.protocol, info.cipher);
652 else
653 -- TLS session might not be ready yet
654 line[#line+1] = "(cipher info unavailable)";
655 end
656 if sock.getsniname then
657 local name = sock:getsniname();
658 if name then
659 line[#line+1] = ("(SNI:%q)"):format(name);
660 end
661 end
662 if sock.getalpn then
663 local proto = sock:getalpn();
664 if proto then
665 line[#line+1] = ("(ALPN:%q)"):format(proto);
666 end
667 end
668 end
669 else
670 line[#line+1] = "(insecure)";
671 end
672 return table.concat(line, " ");
673 end
674
675 def_env.c2s = {};
676
677 local function get_jid(session)
678 if session.username then
679 return session.full_jid or jid_join(session.username, session.host, session.resource);
680 end
681
682 local conn = session.conn;
683 local ip = session.ip or "?";
684 local clientport = conn and conn:clientport() or "?";
685 local serverip = conn and conn.server and conn:server():ip() or "?";
686 local serverport = conn and conn:serverport() or "?"
687 return jid_join("["..ip.."]:"..clientport, session.host or "["..serverip.."]:"..serverport);
688 end
689
690 local function get_c2s()
691 local c2s = array.collect(values(prosody.full_sessions));
692 c2s:append(array.collect(values(module:shared"/*/c2s/sessions")));
693 c2s:append(array.collect(values(module:shared"/*/bosh/sessions")));
694 c2s:unique();
695 return c2s;
696 end
697
698 local function show_c2s(callback)
699 get_c2s():sort(function(a, b)
700 if a.host == b.host then
701 if a.username == b.username then
702 return (a.resource or "") > (b.resource or "");
703 end
704 return (a.username or "") > (b.username or "");
705 end
706 return _sort_hosts(a.host or "", b.host or "");
707 end):map(function (session)
708 callback(get_jid(session), session)
709 end);
710 end
711
712 function def_env.c2s:count()
713 local c2s = get_c2s();
714 return true, "Total: ".. #c2s .." clients";
715 end
716
717 function def_env.c2s:show(match_jid, annotate)
718 local print, count = self.session.print, 0;
719 annotate = annotate or session_flags;
720 local curr_host = false;
721 show_c2s(function (jid, session)
722 if curr_host ~= session.host then
723 curr_host = session.host;
724 print(curr_host or "(not connected to any host yet)");
725 end
726 if (not match_jid) or jid:match(match_jid) then
727 count = count + 1;
728 print(annotate(session, { " ", jid }));
729 end
730 end);
731 return true, "Total: "..count.." clients";
732 end
733
734 function def_env.c2s:show_insecure(match_jid)
735 local print, count = self.session.print, 0;
736 show_c2s(function (jid, session)
737 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
738 count = count + 1;
739 print(jid);
740 end
741 end);
742 return true, "Total: "..count.." insecure client connections";
743 end
744
745 function def_env.c2s:show_secure(match_jid)
746 local print, count = self.session.print, 0;
747 show_c2s(function (jid, session)
748 if ((not match_jid) or jid:match(match_jid)) and session.secure then
749 count = count + 1;
750 print(jid);
751 end
752 end);
753 return true, "Total: "..count.." secure client connections";
754 end
755
756 function def_env.c2s:show_tls(match_jid)
757 return self:show(match_jid, tls_info);
758 end
759
760 local function build_reason(text, condition)
761 if text or condition then
762 return {
763 text = text,
764 condition = condition or "undefined-condition",
765 };
766 end
767 end
768
769 function def_env.c2s:close(match_jid, text, condition)
770 local count = 0;
771 show_c2s(function (jid, session)
772 if jid == match_jid or jid_bare(jid) == match_jid then
773 count = count + 1;
774 session:close(build_reason(text, condition));
775 end
776 end);
777 return true, "Total: "..count.." sessions closed";
778 end
779
780 function def_env.c2s:closeall(text, condition)
781 local count = 0;
782 --luacheck: ignore 212/jid
783 show_c2s(function (jid, session)
784 count = count + 1;
785 session:close(build_reason(text, condition));
786 end);
787 return true, "Total: "..count.." sessions closed";
788 end
789
790
791 def_env.s2s = {};
792 function def_env.s2s:show(match_jid, annotate)
793 local print = self.session.print;
794 annotate = annotate or session_flags;
795
796 local count_in, count_out = 0,0;
797 local s2s_list = { };
798
799 local s2s_sessions = module:shared"/*/s2s/sessions";
800 for _, session in pairs(s2s_sessions) do
801 local remotehost, localhost, direction;
802 if session.direction == "outgoing" then
803 direction = "->";
804 count_out = count_out + 1;
805 remotehost, localhost = session.to_host or "?", session.from_host or "?";
806 else
807 direction = "<-";
808 count_in = count_in + 1;
809 remotehost, localhost = session.from_host or "?", session.to_host or "?";
810 end
811 local sess_lines = { l = localhost, r = remotehost,
812 annotate(session, { "", direction, remotehost or "?" })};
813
814 if (not match_jid) or remotehost:match(match_jid) or localhost:match(match_jid) then
815 table.insert(s2s_list, sess_lines);
816 -- luacheck: ignore 421/print
817 local print = function (s) table.insert(sess_lines, " "..s); end
818 if session.sendq then
819 print("There are "..#session.sendq.." queued outgoing stanzas for this connection");
820 end
821 if session.type == "s2sout_unauthed" then
822 if session.connecting then
823 print("Connection not yet established");
824 if not session.srv_hosts then
825 if not session.conn then
826 print("We do not yet have a DNS answer for this host's SRV records");
827 else
828 print("This host has no SRV records, using A record instead");
829 end
830 elseif session.srv_choice then
831 print("We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
832 local srv_choice = session.srv_hosts[session.srv_choice];
833 print("Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
834 end
835 elseif session.notopen then
836 print("The <stream> has not yet been opened");
837 elseif not session.dialback_key then
838 print("Dialback has not been initiated yet");
839 elseif session.dialback_key then
840 print("Dialback has been requested, but no result received");
841 end
842 end
843 if session.type == "s2sin_unauthed" then
844 print("Connection not yet authenticated");
845 elseif session.type == "s2sin" then
846 for name in pairs(session.hosts) do
847 if name ~= session.from_host then
848 print("also hosts "..tostring(name));
849 end
850 end
851 end
852 end
853 end
854
855 -- Sort by local host, then remote host
856 table.sort(s2s_list, function(a,b)
857 if a.l == b.l then return _sort_hosts(a.r, b.r); end
858 return _sort_hosts(a.l, b.l);
859 end);
860 local lasthost;
861 for _, sess_lines in ipairs(s2s_list) do
862 if sess_lines.l ~= lasthost then print(sess_lines.l); lasthost=sess_lines.l end
863 for _, line in ipairs(sess_lines) do print(line); end
864 end
865 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
866 end
867
868 function def_env.s2s:show_tls(match_jid)
869 return self:show(match_jid, tls_info);
870 end
871
872 local function print_subject(print, subject)
873 for _, entry in ipairs(subject) do
874 print(
875 (" %s: %q"):format(
876 entry.name or entry.oid,
877 entry.value:gsub("[\r\n%z%c]", " ")
878 )
879 );
880 end
881 end
882
883 -- As much as it pains me to use the 0-based depths that OpenSSL does,
884 -- I think there's going to be more confusion among operators if we
885 -- break from that.
886 local function print_errors(print, errors)
887 for depth, t in pairs(errors) do
888 print(
889 (" %d: %s"):format(
890 depth-1,
891 table.concat(t, "\n| ")
892 )
893 );
894 end
895 end
896
897 function def_env.s2s:showcert(domain)
898 local print = self.session.print;
899 local s2s_sessions = module:shared"/*/s2s/sessions";
900 local domain_sessions = set.new(array.collect(values(s2s_sessions)))
901 /function(session) return (session.to_host == domain or session.from_host == domain) and session or nil; end;
902 local cert_set = {};
903 for session in domain_sessions do
904 local conn = session.conn;
905 conn = conn and conn:socket();
906 if not conn.getpeerchain then
907 if conn.dohandshake then
908 error("This version of LuaSec does not support certificate viewing");
909 end
910 else
911 local cert = conn:getpeercertificate();
912 if cert then
913 local certs = conn:getpeerchain();
914 local digest = cert:digest("sha1");
915 if not cert_set[digest] then
916 local chain_valid, chain_errors = conn:getpeerverification();
917 cert_set[digest] = {
918 {
919 from = session.from_host,
920 to = session.to_host,
921 direction = session.direction
922 };
923 chain_valid = chain_valid;
924 chain_errors = chain_errors;
925 certs = certs;
926 };
927 else
928 table.insert(cert_set[digest], {
929 from = session.from_host,
930 to = session.to_host,
931 direction = session.direction
932 });
933 end
934 end
935 end
936 end
937 local domain_certs = array.collect(values(cert_set));
938 -- Phew. We now have a array of unique certificates presented by domain.
939 local n_certs = #domain_certs;
940
941 if n_certs == 0 then
942 return "No certificates found for "..domain;
943 end
944
945 local function _capitalize_and_colon(byte)
946 return string.upper(byte)..":";
947 end
948 local function pretty_fingerprint(hash)
949 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
950 end
951
952 for cert_info in values(domain_certs) do
953 local certs = cert_info.certs;
954 local cert = certs[1];
955 print("---")
956 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
957 print("");
958 local n_streams = #cert_info;
959 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
960 for _, stream in ipairs(cert_info) do
961 if stream.direction == "incoming" then
962 print(" "..stream.to.." <- "..stream.from);
963 else
964 print(" "..stream.from.." -> "..stream.to);
965 end
966 end
967 print("");
968 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
969 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
970 if chain_valid then
971 print("Trusted certificate: Yes");
972 else
973 print("Trusted certificate: No");
974 print_errors(print, errors);
975 end
976 print("");
977 print("Issuer: ");
978 print_subject(print, cert:issuer());
979 print("");
980 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
981 print("Subject:");
982 print_subject(print, cert:subject());
983 end
984 print("---");
985 return ("Showing "..n_certs.." certificate"
986 ..(n_certs==1 and "" or "s")
987 .." presented by "..domain..".");
988 end
989
990 function def_env.s2s:close(from, to, text, condition)
991 local print, count = self.session.print, 0;
992 local s2s_sessions = module:shared"/*/s2s/sessions";
993
994 local match_id;
995 if from and not to then
996 match_id, from = from, nil;
997 elseif not to then
998 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
999 elseif from == to then
1000 return false, "Both from and to are the same... you can't do that :)";
1001 end
1002
1003 for _, session in pairs(s2s_sessions) do
1004 local id = session.id or (session.type..tostring(session):match("[a-f0-9]+$"));
1005 if (match_id and match_id == id)
1006 or (session.from_host == from and session.to_host == to) then
1007 print(("Closing connection from %s to %s [%s]"):format(session.from_host, session.to_host, id));
1008 (session.close or s2smanager.destroy_session)(session, build_reason(text, condition));
1009 count = count + 1 ;
1010 end
1011 end
1012 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
1013 end
1014
1015 function def_env.s2s:closeall(host, text, condition)
1016 local count = 0;
1017 local s2s_sessions = module:shared"/*/s2s/sessions";
1018 for _,session in pairs(s2s_sessions) do
1019 if not host or session.from_host == host or session.to_host == host then
1020 session:close(build_reason(text, condition));
1021 count = count + 1;
1022 end
1023 end
1024 if count == 0 then return false, "No sessions to close.";
1025 else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
1026 end
1027
1028 def_env.host = {}; def_env.hosts = def_env.host;
1029
1030 function def_env.host:activate(hostname, config)
1031 return hostmanager.activate(hostname, config);
1032 end
1033 function def_env.host:deactivate(hostname, reason)
1034 return hostmanager.deactivate(hostname, reason);
1035 end
1036
1037 function def_env.host:list()
1038 local print = self.session.print;
1039 local i = 0;
1040 local type;
1041 for host, host_session in iterators.sorted_pairs(prosody.hosts, _sort_hosts) do
1042 i = i + 1;
1043 type = host_session.type;
1044 if type == "local" then
1045 print(host);
1046 else
1047 type = module:context(host):get_option_string("component_module", type);
1048 if type ~= "component" then
1049 type = type .. " component";
1050 end
1051 print(("%s (%s)"):format(host, type));
1052 end
1053 end
1054 return true, i.." hosts";
1055 end
1056
1057 def_env.port = {};
1058
1059 function def_env.port:list()
1060 local print = self.session.print;
1061 local services = portmanager.get_active_services().data;
1062 local n_services, n_ports = 0, 0;
1063 for service, interfaces in iterators.sorted_pairs(services) do
1064 n_services = n_services + 1;
1065 local ports_list = {};
1066 for interface, ports in pairs(interfaces) do
1067 for port in pairs(ports) do
1068 table.insert(ports_list, "["..interface.."]:"..port);
1069 end
1070 end
1071 n_ports = n_ports + #ports_list;
1072 print(service..": "..table.concat(ports_list, ", "));
1073 end
1074 return true, n_services.." services listening on "..n_ports.." ports";
1075 end
1076
1077 function def_env.port:close(close_port, close_interface)
1078 close_port = assert(tonumber(close_port), "Invalid port number");
1079 local n_closed = 0;
1080 local services = portmanager.get_active_services().data;
1081 for service, interfaces in pairs(services) do -- luacheck: ignore 213
1082 for interface, ports in pairs(interfaces) do
1083 if not close_interface or close_interface == interface then
1084 if ports[close_port] then
1085 self.session.print("Closing ["..interface.."]:"..close_port.."...");
1086 local ok, err = portmanager.close(interface, close_port)
1087 if not ok then
1088 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
1089 else
1090 n_closed = n_closed + 1;
1091 end
1092 end
1093 end
1094 end
1095 end
1096 return true, "Closed "..n_closed.." ports";
1097 end
1098
1099 def_env.muc = {};
1100
1101 local console_room_mt = {
1102 __index = function (self, k) return self.room[k]; end;
1103 __tostring = function (self)
1104 return "MUC room <"..self.room.jid..">";
1105 end;
1106 };
1107
1108 local function check_muc(jid)
1109 local room_name, host = jid_split(jid);
1110 if not prosody.hosts[host] then
1111 return nil, "No such host: "..host;
1112 elseif not prosody.hosts[host].modules.muc then
1113 return nil, "Host '"..host.."' is not a MUC service";
1114 end
1115 return room_name, host;
1116 end
1117
1118 function def_env.muc:create(room_jid, config)
1119 local room_name, host = check_muc(room_jid);
1120 if not room_name then
1121 return room_name, host;
1122 end
1123 if not room_name then return nil, host end
1124 if config ~= nil and type(config) ~= "table" then return nil, "Config must be a table"; end
1125 if prosody.hosts[host].modules.muc.get_room_from_jid(room_jid) then return nil, "Room exists already" end
1126 return prosody.hosts[host].modules.muc.create_room(room_jid, config);
1127 end
1128
1129 function def_env.muc:room(room_jid)
1130 local room_name, host = check_muc(room_jid);
1131 if not room_name then
1132 return room_name, host;
1133 end
1134 local room_obj = prosody.hosts[host].modules.muc.get_room_from_jid(room_jid);
1135 if not room_obj then
1136 return nil, "No such room: "..room_jid;
1137 end
1138 return setmetatable({ room = room_obj }, console_room_mt);
1139 end
1140
1141 function def_env.muc:list(host)
1142 local host_session = prosody.hosts[host];
1143 if not host_session or not host_session.modules.muc then
1144 return nil, "Please supply the address of a local MUC component";
1145 end
1146 local print = self.session.print;
1147 local c = 0;
1148 for room in host_session.modules.muc.each_room() do
1149 print(room.jid);
1150 c = c + 1;
1151 end
1152 return true, c.." rooms";
1153 end
1154
1155 local um = require"core.usermanager";
1156
1157 def_env.user = {};
1158 function def_env.user:create(jid, password)
1159 local username, host = jid_split(jid);
1160 if not prosody.hosts[host] then
1161 return nil, "No such host: "..host;
1162 elseif um.user_exists(username, host) then
1163 return nil, "User exists";
1164 end
1165 local ok, err = um.create_user(username, password, host);
1166 if ok then
1167 return true, "User created";
1168 else
1169 return nil, "Could not create user: "..err;
1170 end
1171 end
1172
1173 function def_env.user:delete(jid)
1174 local username, host = jid_split(jid);
1175 if not prosody.hosts[host] then
1176 return nil, "No such host: "..host;
1177 elseif not um.user_exists(username, host) then
1178 return nil, "No such user";
1179 end
1180 local ok, err = um.delete_user(username, host);
1181 if ok then
1182 return true, "User deleted";
1183 else
1184 return nil, "Could not delete user: "..err;
1185 end
1186 end
1187
1188 function def_env.user:password(jid, password)
1189 local username, host = jid_split(jid);
1190 if not prosody.hosts[host] then
1191 return nil, "No such host: "..host;
1192 elseif not um.user_exists(username, host) then
1193 return nil, "No such user";
1194 end
1195 local ok, err = um.set_password(username, password, host, nil);
1196 if ok then
1197 return true, "User password changed";
1198 else
1199 return nil, "Could not change password for user: "..err;
1200 end
1201 end
1202
1203 function def_env.user:list(host, pat)
1204 if not host then
1205 return nil, "No host given";
1206 elseif not prosody.hosts[host] then
1207 return nil, "No such host";
1208 end
1209 local print = self.session.print;
1210 local total, matches = 0, 0;
1211 for user in um.users(host) do
1212 if not pat or user:match(pat) then
1213 print(user.."@"..host);
1214 matches = matches + 1;
1215 end
1216 total = total + 1;
1217 end
1218 return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
1219 end
1220
1221 def_env.xmpp = {};
1222
1223 local st = require "util.stanza";
1224 local new_id = require "util.id".medium;
1225 function def_env.xmpp:ping(localhost, remotehost, timeout)
1226 localhost = select(2, jid_split(localhost));
1227 remotehost = select(2, jid_split(remotehost));
1228 if not localhost then
1229 return nil, "Invalid sender hostname";
1230 elseif not prosody.hosts[localhost] then
1231 return nil, "No such local host";
1232 end
1233 if not remotehost then
1234 return nil, "Invalid destination hostname";
1235 elseif prosody.hosts[remotehost] then
1236 return nil, "Both hosts are local";
1237 end
1238 local iq = st.iq{ from=localhost, to=remotehost, type="get", id=new_id()}
1239 :tag("ping", {xmlns="urn:xmpp:ping"});
1240 local time_start = time.now();
1241 local ret, err = async.wait(module:context(localhost):send_iq(iq, nil, timeout));
1242 if ret then
1243 return true, ("pong from %s in %gs"):format(ret.stanza.attr.from, time.now() - time_start);
1244 else
1245 return false, tostring(err);
1246 end
1247 end
1248
1249 def_env.dns = {};
1250 local adns = require"net.adns";
1251
1252 local function get_resolver(session)
1253 local resolver = session.dns_resolver;
1254 if not resolver then
1255 resolver = adns.resolver();
1256 session.dns_resolver = resolver;
1257 end
1258 return resolver;
1259 end
1260
1261 function def_env.dns:lookup(name, typ, class)
1262 local resolver = get_resolver(self.session);
1263 local ret, err = async.wait(resolver:lookup_promise(name, typ, class));
1264 if ret then
1265 return true, ret;
1266 elseif err then
1267 return false, err;
1268 end
1269 end
1270
1271 function def_env.dns:addnameserver(...)
1272 local resolver = get_resolver(self.session);
1273 resolver._resolver:addnameserver(...)
1274 return true
1275 end
1276
1277 function def_env.dns:setnameserver(...)
1278 local resolver = get_resolver(self.session);
1279 resolver._resolver:setnameserver(...)
1280 return true
1281 end
1282
1283 function def_env.dns:purge()
1284 local resolver = get_resolver(self.session);
1285 resolver._resolver:purge()
1286 return true
1287 end
1288
1289 function def_env.dns:cache()
1290 local resolver = get_resolver(self.session);
1291 return true, "Cache:\n"..tostring(resolver._resolver.cache)
1292 end
1293
1294 def_env.http = {};
1295
1296 function def_env.http:list(hosts)
1297 local print = self.session.print;
1298
1299 for host in get_hosts_set(hosts) do
1300 local http_apps = modulemanager.get_items("http-provider", host);
1301 if #http_apps > 0 then
1302 local http_host = module:context(host):get_option_string("http_host");
1303 print("HTTP endpoints on "..host..(http_host and (" (using "..http_host.."):") or ":"));
1304 for _, provider in ipairs(http_apps) do
1305 local url = module:context(host):http_url(provider.name, provider.default_path);
1306 print("", url);
1307 end
1308 print("");
1309 end
1310 end
1311
1312 local default_host = module:get_option_string("http_default_host");
1313 if not default_host then
1314 print("HTTP requests to unknown hosts will return 404 Not Found");
1315 else
1316 print("HTTP requests to unknown hosts will be handled by "..default_host);
1317 end
1318 return true;
1319 end
1320
1321 def_env.debug = {};
1322
1323 function def_env.debug:logevents(host)
1324 helpers.log_host_events(host);
1325 return true;
1326 end
1327
1328 function def_env.debug:events(host, event)
1329 local events_obj;
1330 if host and host ~= "*" then
1331 if host == "http" then
1332 events_obj = require "net.http.server"._events;
1333 elseif not prosody.hosts[host] then
1334 return false, "Unknown host: "..host;
1335 else
1336 events_obj = prosody.hosts[host].events;
1337 end
1338 else
1339 events_obj = prosody.events;
1340 end
1341 return true, helpers.show_events(events_obj, event);
1342 end
1343
1344 function def_env.debug:timers()
1345 local print = self.session.print;
1346 local add_task = require"util.timer".add_task;
1347 local h, params = add_task.h, add_task.params;
1348 if h then
1349 print("-- util.timer");
1350 for i, id in ipairs(h.ids) do
1351 if not params[id] then
1352 print(os.date("%F %T", h.priorities[i]), h.items[id]);
1353 elseif not params[id].callback then
1354 print(os.date("%F %T", h.priorities[i]), h.items[id], unpack(params[id]));
1355 else
1356 print(os.date("%F %T", h.priorities[i]), params[id].callback, unpack(params[id]));
1357 end
1358 end
1359 end
1360 if server.event_base then
1361 local count = 0;
1362 for _, v in pairs(debug.getregistry()) do
1363 if type(v) == "function" and v.callback and v.callback == add_task._on_timer then
1364 count = count + 1;
1365 end
1366 end
1367 print(count .. " libevent callbacks");
1368 end
1369 if h then
1370 local next_time = h:peek();
1371 if next_time then
1372 return true, os.date("Next event at %F %T (in %%.6fs)", next_time):format(next_time - time.now());
1373 end
1374 end
1375 return true;
1376 end
1377
1378 -- COMPAT: debug:timers() was timer:info() for some time in trunk
1379 def_env.timer = { info = def_env.debug.timers };
1380
1381 module:hook("server-stopping", function(event)
1382 for _, session in pairs(sessions) do
1383 session.print("Shutting down: "..(event.reason or "unknown reason"));
1384 end
1385 end);
1386
1387 def_env.stats = {};
1388
1389 local function format_stat(type, value, ref_value)
1390 ref_value = ref_value or value;
1391 --do return tostring(value) end
1392 if type == "duration" then
1393 if ref_value < 0.001 then
1394 return ("%g µs"):format(value*1000000);
1395 elseif ref_value < 0.9 then
1396 return ("%0.2f ms"):format(value*1000);
1397 end
1398 return ("%0.2f"):format(value);
1399 elseif type == "size" then
1400 if ref_value > 1048576 then
1401 return ("%d MB"):format(value/1048576);
1402 elseif ref_value > 1024 then
1403 return ("%d KB"):format(value/1024);
1404 end
1405 return ("%d bytes"):format(value);
1406 elseif type == "rate" then
1407 if ref_value < 0.9 then
1408 return ("%0.2f/min"):format(value*60);
1409 end
1410 return ("%0.2f/sec"):format(value);
1411 end
1412 return tostring(value);
1413 end
1414
1415 local stats_methods = {};
1416 function stats_methods:bounds(_lower, _upper)
1417 for _, stat_info in ipairs(self) do
1418 local data = stat_info[4];
1419 if data then
1420 local lower = _lower or data.min;
1421 local upper = _upper or data.max;
1422 local new_data = {
1423 min = lower;
1424 max = upper;
1425 samples = {};
1426 sample_count = 0;
1427 count = data.count;
1428 units = data.units;
1429 };
1430 local sum = 0;
1431 for _, v in ipairs(data.samples) do
1432 if v > upper then
1433 break;
1434 elseif v>=lower then
1435 table.insert(new_data.samples, v);
1436 sum = sum + v;
1437 end
1438 end
1439 new_data.sample_count = #new_data.samples;
1440 stat_info[4] = new_data;
1441 stat_info[3] = sum/new_data.sample_count;
1442 end
1443 end
1444 return self;
1445 end
1446
1447 function stats_methods:trim(lower, upper)
1448 upper = upper or (100-lower);
1449 local statistics = require "util.statistics";
1450 for _, stat_info in ipairs(self) do
1451 -- Strip outliers
1452 local data = stat_info[4];
1453 if data then
1454 local new_data = {
1455 min = statistics.get_percentile(data, lower);
1456 max = statistics.get_percentile(data, upper);
1457 samples = {};
1458 sample_count = 0;
1459 count = data.count;
1460 units = data.units;
1461 };
1462 local sum = 0;
1463 for _, v in ipairs(data.samples) do
1464 if v > new_data.max then
1465 break;
1466 elseif v>=new_data.min then
1467 table.insert(new_data.samples, v);
1468 sum = sum + v;
1469 end
1470 end
1471 new_data.sample_count = #new_data.samples;
1472 stat_info[4] = new_data;
1473 stat_info[3] = sum/new_data.sample_count;
1474 end
1475 end
1476 return self;
1477 end
1478
1479 function stats_methods:max(upper)
1480 return self:bounds(nil, upper);
1481 end
1482
1483 function stats_methods:min(lower)
1484 return self:bounds(lower, nil);
1485 end
1486
1487 function stats_methods:summary()
1488 local statistics = require "util.statistics";
1489 for _, stat_info in ipairs(self) do
1490 local type, value, data = stat_info[2], stat_info[3], stat_info[4];
1491 if data and data.samples then
1492 table.insert(stat_info.output, string.format("Count: %d (%d captured)",
1493 data.count,
1494 data.sample_count
1495 ));
1496 table.insert(stat_info.output, string.format("Min: %s Mean: %s Max: %s",
1497 format_stat(type, data.min),
1498 format_stat(type, value),
1499 format_stat(type, data.max)
1500 ));
1501 table.insert(stat_info.output, string.format("Q1: %s Median: %s Q3: %s",
1502 format_stat(type, statistics.get_percentile(data, 25)),
1503 format_stat(type, statistics.get_percentile(data, 50)),
1504 format_stat(type, statistics.get_percentile(data, 75))
1505 ));
1506 end
1507 end
1508 return self;
1509 end
1510
1511 function stats_methods:cfgraph()
1512 for _, stat_info in ipairs(self) do
1513 local name, type, value, data = unpack(stat_info, 1, 4); -- luacheck: ignore 211
1514 local function print(s)
1515 table.insert(stat_info.output, s);
1516 end
1517
1518 if data and data.sample_count and data.sample_count > 0 then
1519 local raw_histogram = require "util.statistics".get_histogram(data);
1520
1521 local graph_width, graph_height = 50, 10;
1522 local eighth_chars = " ▁▂▃▄▅▆▇█";
1523
1524 local range = data.max - data.min;
1525
1526 if range > 0 then
1527 local x_scaling = #raw_histogram/graph_width;
1528 local histogram = {};
1529 for i = 1, graph_width do
1530 histogram[i] = math.max(raw_histogram[i*x_scaling-1] or 0, raw_histogram[i*x_scaling] or 0);
1531 end
1532
1533 print("");
1534 print(("_"):rep(52)..format_stat(type, data.max));
1535 for row = graph_height, 1, -1 do
1536 local row_chars = {};
1537 local min_eighths, max_eighths = 8, 0;
1538 for i = 1, #histogram do
1539 local char_eighths = math.ceil(math.max(math.min((graph_height/(data.max/histogram[i]))-(row-1), 1), 0)*8);
1540 if char_eighths < min_eighths then
1541 min_eighths = char_eighths;
1542 end
1543 if char_eighths > max_eighths then
1544 max_eighths = char_eighths;
1545 end
1546 if char_eighths == 0 then
1547 row_chars[i] = "-";
1548 else
1549 local char = eighth_chars:sub(char_eighths*3+1, char_eighths*3+3);
1550 row_chars[i] = char;
1551 end
1552 end
1553 print(table.concat(row_chars).."|-"..format_stat(type, data.max/(graph_height/(row-0.5))));
1554 end
1555 print(("\\ "):rep(11));
1556 local x_labels = {};
1557 for i = 1, 11 do
1558 local s = ("%-4s"):format((i-1)*10);
1559 if #s > 4 then
1560 s = s:sub(1, 3).."…";
1561 end
1562 x_labels[i] = s;
1563 end
1564 print(" "..table.concat(x_labels, " "));
1565 local units = "%";
1566 local margin = math.floor((graph_width-#units)/2);
1567 print((" "):rep(margin)..units);
1568 else
1569 print("[range too small to graph]");
1570 end
1571 print("");
1572 end
1573 end
1574 return self;
1575 end
1576
1577 function stats_methods:histogram()
1578 for _, stat_info in ipairs(self) do
1579 local name, type, value, data = unpack(stat_info, 1, 4); -- luacheck: ignore 211
1580 local function print(s)
1581 table.insert(stat_info.output, s);
1582 end
1583
1584 if not data then
1585 print("[no data]");
1586 return self;
1587 elseif not data.sample_count then
1588 print("[not a sampled metric type]");
1589 return self;
1590 end
1591
1592 local graph_width, graph_height = 50, 10;
1593 local eighth_chars = " ▁▂▃▄▅▆▇█";
1594
1595 local range = data.max - data.min;
1596
1597 if range > 0 then
1598 local n_buckets = graph_width;
1599
1600 local histogram = {};
1601 for i = 1, n_buckets do
1602 histogram[i] = 0;
1603 end
1604 local max_bin_samples = 0;
1605 for _, d in ipairs(data.samples) do
1606 local bucket = math.floor(1+(n_buckets-1)/(range/(d-data.min)));
1607 histogram[bucket] = histogram[bucket] + 1;
1608 if histogram[bucket] > max_bin_samples then
1609 max_bin_samples = histogram[bucket];
1610 end
1611 end
1612
1613 print("");
1614 print(("_"):rep(52)..max_bin_samples);
1615 for row = graph_height, 1, -1 do
1616 local row_chars = {};
1617 local min_eighths, max_eighths = 8, 0;
1618 for i = 1, #histogram do
1619 local char_eighths = math.ceil(math.max(math.min((graph_height/(max_bin_samples/histogram[i]))-(row-1), 1), 0)*8);
1620 if char_eighths < min_eighths then
1621 min_eighths = char_eighths;
1622 end
1623 if char_eighths > max_eighths then
1624 max_eighths = char_eighths;
1625 end
1626 if char_eighths == 0 then
1627 row_chars[i] = "-";
1628 else
1629 local char = eighth_chars:sub(char_eighths*3+1, char_eighths*3+3);
1630 row_chars[i] = char;
1631 end
1632 end
1633 print(table.concat(row_chars).."|-"..math.ceil((max_bin_samples/graph_height)*(row-0.5)));
1634 end
1635 print(("\\ "):rep(11));
1636 local x_labels = {};
1637 for i = 1, 11 do
1638 local s = ("%-4s"):format(format_stat(type, data.min+range*i/11, data.min):match("^%S+"));
1639 if #s > 4 then
1640 s = s:sub(1, 3).."…";
1641 end
1642 x_labels[i] = s;
1643 end
1644 print(" "..table.concat(x_labels, " "));
1645 local units = format_stat(type, data.min):match("%s+(.+)$") or data.units or "";
1646 local margin = math.floor((graph_width-#units)/2);
1647 print((" "):rep(margin)..units);
1648 else
1649 print("[range too small to graph]");
1650 end
1651 print("");
1652 end
1653 return self;
1654 end
1655
1656 local function stats_tostring(stats)
1657 local print = stats.session.print;
1658 for _, stat_info in ipairs(stats) do
1659 if #stat_info.output > 0 then
1660 print("\n#"..stat_info[1]);
1661 print("");
1662 for _, v in ipairs(stat_info.output) do
1663 print(v);
1664 end
1665 print("");
1666 else
1667 print(("%-50s %s"):format(stat_info[1], format_stat(stat_info[2], stat_info[3])));
1668 end
1669 end
1670 return #stats.." statistics displayed";
1671 end
1672
1673 local stats_mt = {__index = stats_methods, __tostring = stats_tostring }
1674 local function new_stats_context(self)
1675 return setmetatable({ session = self.session, stats = true }, stats_mt);
1676 end
1677
1678 function def_env.stats:show(filter)
1679 -- luacheck: ignore 211/changed
1680 local stats, changed, extra = require "core.statsmanager".get_stats();
1681 local available, displayed = 0, 0;
1682 local displayed_stats = new_stats_context(self);
1683 for name, value in iterators.sorted_pairs(stats) do
1684 available = available + 1;
1685 if not filter or name:match(filter) then
1686 displayed = displayed + 1;
1687 local type = name:match(":(%a+)$");
1688 table.insert(displayed_stats, {
1689 name, type, value, extra[name];
1690 output = {};
1691 });
1692 end
1693 end
1694 return displayed_stats;
1695 end
1696
1697
1698
1699 -------------
1700
1701 function printbanner(session)
1702 local option = module:get_option_string("console_banner", "full");
1703 if option == "full" or option == "graphic" then
1704 session.print [[
1705 ____ \ / _
1706 | _ \ _ __ ___ ___ _-_ __| |_ _
1707 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1708 | __/| | | (_) \__ \ |_| | (_| | |_| |
1709 |_| |_| \___/|___/\___/ \__,_|\__, |
1710 A study in simplicity |___/
1711
1712 ]]
1713 end
1714 if option == "short" or option == "full" then
1715 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1716 session.print("You may find more help on using this console in our online documentation at ");
1717 session.print("https://prosody.im/doc/console\n");
1718 end
1719 if option ~= "short" and option ~= "full" and option ~= "graphic" then
1720 session.print(option);
1721 end
1722 end
1723
1724 module:provides("net", { 171 module:provides("net", {
1725 name = "console"; 172 name = "console";
1726 listener = console_listener; 173 listener = console_listener;
1727 default_port = 5582; 174 default_port = 5582;
1728 private = true; 175 private = true;