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