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