2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
13 local prosody = _G.prosody;
14 local hosts = prosody.hosts;
15 local connlisteners_register = require "net.connlisteners".register;
17 local console_listener = { default_port = 5582; default_mode = "*l"; default_interface = "127.0.0.1" };
19 require "util.iterators";
20 local jid_bare = require "util.jid".bare;
21 local set, array = require "util.set", require "util.array";
25 local default_env_mt = { __index = def_env };
27 prosody.console = { commands = commands, env = def_env };
29 local function redirect_output(_G, session)
30 local env = setmetatable({ print = session.print }, { __index = function (t, k) return rawget(_G, k); end, __newindex = function (t, k, v) rawset(_G, k, v); end });
31 env.dofile = function(name)
32 local f, err = loadfile(name);
33 if not f then return f, err; end
34 return setfenv(f, env)();
41 function console:new_session(conn)
42 local w = function(s) conn:write(s:gsub("\n", "\r\n")); end;
43 local session = { conn = conn;
44 send = function (t) w(tostring(t)); end;
45 print = function (...)
47 for i=1,select("#", ...) do
48 t[i] = tostring(select(i, ...));
50 w("| "..table.concat(t, "\t").."\n");
52 disconnect = function () conn:close(); end;
54 session.env = setmetatable({}, default_env_mt);
56 -- Load up environment with helper objects
57 for name, t in pairs(def_env) do
58 if type(t) == "table" then
59 session.env[name] = setmetatable({ session = session }, { __index = t });
68 function console_listener.onconnect(conn)
69 -- Handle new connection
70 local session = console:new_session(conn);
71 sessions[conn] = session;
73 session.send(string.char(0));
76 function console_listener.onincoming(conn, data)
77 local session = sessions[conn];
80 (function(session, data)
83 if data:match("^>") then
84 data = data:gsub("^>", "");
86 elseif data == "\004" then
87 commands["bye"](session, data);
90 local command = data:lower();
91 command = data:match("^%w+") or data:match("%p");
92 if commands[command] then
93 commands[command](session, data);
100 local chunkname = "=console";
101 local chunk, err = loadstring("return "..data, chunkname);
103 chunk, err = loadstring(data, chunkname);
105 err = err:gsub("^%[string .-%]:%d+: ", "");
106 err = err:gsub("^:%d+: ", "");
107 err = err:gsub("'<eof>'", "the end of the line");
108 session.print("Sorry, I couldn't understand that... "..err);
113 setfenv(chunk, (useglobalenv and redirect_output(_G, session)) or session.env or nil);
115 local ranok, taskok, message = pcall(chunk);
117 if not (ranok or message or useglobalenv) and commands[data:lower()] then
118 commands[data:lower()](session, data);
123 session.print("Fatal error while running command, it did not complete");
124 session.print("Error: "..taskok);
129 session.print("Result: "..tostring(taskok));
131 elseif (not taskok) and message then
132 session.print("Command completed with a problem");
133 session.print("Message: "..tostring(message));
137 session.print("OK: "..tostring(message));
140 session.send(string.char(0));
143 function console_listener.ondisconnect(conn, err)
144 local session = sessions[conn];
146 session.disconnect();
147 sessions[conn] = nil;
151 connlisteners_register('console', console_listener);
153 -- Console commands --
154 -- These are simple commands, not valid standalone in Lua
156 function commands.bye(session)
157 session.print("See you! :)");
158 session.disconnect();
160 commands.quit, commands.exit = commands.bye, commands.bye;
162 commands["!"] = function (session, data)
163 if data:match("^!!") then
164 session.print("!> "..session.env._);
165 return console_listener.onincoming(session.conn, session.env._);
167 local old, new = data:match("^!(.-[^\\])!(.-)!$");
169 local ok, res = pcall(string.gsub, session.env._, old, new);
174 session.print("!> "..res);
175 return console_listener.onincoming(session.conn, res);
177 session.print("Sorry, not sure what you want");
180 function commands.help(session, data)
181 local print = session.print;
182 local section = data:match("^help (%w+)");
184 print [[Commands are divided into multiple sections. For help on a particular section, ]]
185 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
187 print [[c2s - Commands to manage local client-to-server sessions]]
188 print [[s2s - Commands to manage sessions between this server and others]]
189 print [[module - Commands to load/reload/unload modules/plugins]]
190 print [[server - Uptime, version, shutting down, etc.]]
191 print [[config - Reloading the configuration, etc.]]
192 print [[console - Help regarding the console itself]]
193 elseif section == "c2s" then
194 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
195 print [[c2s:show_insecure() - Show all unencrypted client connections]]
196 print [[c2s:show_secure() - Show all encrypted client connections]]
197 print [[c2s:close(jid) - Close all sessions for the specified JID]]
198 elseif section == "s2s" then
199 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
200 print [[s2s:close(from, to) - Close a connection from one domain to another]]
201 elseif section == "module" then
202 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
203 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
204 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
205 print [[module:list(host) - List the modules loaded on the specified host]]
206 elseif section == "server" then
207 print [[server:version() - Show the server's version number]]
208 print [[server:uptime() - Show how long the server has been running]]
209 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
210 elseif section == "config" then
211 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
212 elseif section == "console" then
213 print [[Hey! Welcome to Prosody's admin console.]]
214 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
215 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
216 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
218 print [[For now we offer a couple of handy shortcuts:]]
219 print [[!! - Repeat the last command]]
220 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
222 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
223 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
224 print [[the running server. Great fun, but be careful not to break anything :)]]
229 -- Session environment --
230 -- Anything in def_env will be accessible within the session as a global variable
234 function def_env.server:insane_reload()
235 prosody.unlock_globals();
237 prosody = _G.prosody;
238 return true, "Server reloaded";
241 function def_env.server:version()
242 return true, tostring(prosody.version or "unknown");
245 function def_env.server:uptime()
246 local t = os.time()-prosody.start_time;
247 local seconds = t%60;
248 t = (t - seconds)/60;
249 local minutes = t%60;
250 t = (t - minutes)/60;
254 return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
255 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
256 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
259 function def_env.server:shutdown(reason)
260 prosody.shutdown(reason);
261 return true, "Shutdown initiated";
266 local function get_hosts_set(hosts, module)
267 if type(hosts) == "table" then
269 return set.new(hosts);
270 elseif hosts._items then
273 elseif type(hosts) == "string" then
274 return set.new { hosts };
275 elseif hosts == nil then
276 local mm = require "modulemanager";
277 return set.new(array.collect(keys(prosody.hosts)))
278 / function (host) return prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module); end;
282 function def_env.module:load(name, hosts, config)
283 local mm = require "modulemanager";
285 hosts = get_hosts_set(hosts);
287 -- Load the module for each host
288 local ok, err, count = true, nil, 0;
290 if (not mm.is_loaded(host, name)) then
291 ok, err = mm.load(host, name, config);
294 self.session.print(err or "Unknown error loading module");
297 self.session.print("Loaded for "..host);
302 return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
305 function def_env.module:unload(name, hosts)
306 local mm = require "modulemanager";
308 hosts = get_hosts_set(hosts, name);
310 -- Unload the module for each host
311 local ok, err, count = true, nil, 0;
313 if mm.is_loaded(host, name) then
314 ok, err = mm.unload(host, name);
317 self.session.print(err or "Unknown error unloading module");
320 self.session.print("Unloaded from "..host);
324 return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
327 function def_env.module:reload(name, hosts)
328 local mm = require "modulemanager";
330 hosts = get_hosts_set(hosts, name);
332 -- Reload the module for each host
333 local ok, err, count = true, nil, 0;
335 if mm.is_loaded(host, name) then
336 ok, err = mm.reload(host, name);
339 self.session.print(err or "Unknown error reloading module");
345 self.session.print("Reloaded on "..host);
349 return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
352 function def_env.module:list(hosts)
354 hosts = array.collect(keys(prosody.hosts));
356 if type(hosts) == "string" then
359 if type(hosts) ~= "table" then
360 return false, "Please supply a host or a list of hosts you would like to see";
363 local print = self.session.print;
364 for _, host in ipairs(hosts) do
366 local modules = array.collect(keys(prosody.hosts[host] and prosody.hosts[host].modules or {})):sort();
367 if #modules == 0 then
368 if prosody.hosts[host] then
369 print(" No modules loaded");
371 print(" Host not found");
374 for _, name in ipairs(modules) do
382 function def_env.config:load(filename, format)
383 local config_load = require "core.configmanager".load;
384 local ok, err = config_load(filename, format);
386 return false, err or "Unknown error loading config";
388 return true, "Config loaded";
391 function def_env.config:get(host, section, key)
392 local config_get = require "core.configmanager".get
393 return true, tostring(config_get(host, section, key));
396 function def_env.config:reload()
397 local ok, err = prosody.reload_config();
398 return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
402 function def_env.hosts:list()
403 for host, host_session in pairs(hosts) do
404 self.session.print(host);
409 function def_env.hosts:add(name)
414 local function show_c2s(callback)
415 for hostname, host in pairs(hosts) do
416 for username, user in pairs(host.sessions or {}) do
417 for resource, session in pairs(user.sessions or {}) do
418 local jid = username.."@"..hostname.."/"..resource;
419 callback(jid, session);
425 function def_env.c2s:show(match_jid)
426 local print, count = self.session.print, 0;
428 show_c2s(function (jid, session)
429 if curr_host ~= session.host then
430 curr_host = session.host;
433 if (not match_jid) or jid:match(match_jid) then
435 local status, priority = "unavailable", tostring(session.priority or "-");
436 if session.presence then
437 status = session.presence:child_with_name("show");
439 status = status:get_text() or "[invalid!]";
441 status = "available";
444 print(" "..jid.." - "..status.."("..priority..")");
447 return true, "Total: "..count.." clients";
450 function def_env.c2s:show_insecure(match_jid)
451 local print, count = self.session.print, 0;
452 show_c2s(function (jid, session)
453 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
458 return true, "Total: "..count.." insecure client connections";
461 function def_env.c2s:show_secure(match_jid)
462 local print, count = self.session.print, 0;
463 show_c2s(function (jid, session)
464 if ((not match_jid) or jid:match(match_jid)) and session.secure then
469 return true, "Total: "..count.." secure client connections";
472 function def_env.c2s:close(match_jid)
473 local print, count = self.session.print, 0;
474 show_c2s(function (jid, session)
475 if jid == match_jid or jid_bare(jid) == match_jid then
480 return true, "Total: "..count.." sessions closed";
484 function def_env.s2s:show(match_jid)
485 local _print = self.session.print;
486 local print = self.session.print;
488 local count_in, count_out = 0,0;
490 for host, host_session in pairs(hosts) do
491 print = function (...) _print(host); _print(...); print = _print; end
492 for remotehost, session in pairs(host_session.s2sout) do
493 if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
494 count_out = count_out + 1;
495 print(" "..host.." -> "..remotehost..(session.secure and " (encrypted)" or "")..(session.compressed and " (compressed)" or ""));
496 if session.sendq then
497 print(" There are "..#session.sendq.." queued outgoing stanzas for this connection");
499 if session.type == "s2sout_unauthed" then
500 if session.connecting then
501 print(" Connection not yet established");
502 if not session.srv_hosts then
503 if not session.conn then
504 print(" We do not yet have a DNS answer for this host's SRV records");
506 print(" This host has no SRV records, using A record instead");
508 elseif session.srv_choice then
509 print(" We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
510 local srv_choice = session.srv_hosts[session.srv_choice];
511 print(" Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
513 elseif session.notopen then
514 print(" The <stream> has not yet been opened");
515 elseif not session.dialback_key then
516 print(" Dialback has not been initiated yet");
517 elseif session.dialback_key then
518 print(" Dialback has been requested, but no result received");
523 local subhost_filter = function (h)
524 return (match_jid and h:match(match_jid));
526 for session in pairs(incoming_s2s) do
527 if session.to_host == host and ((not match_jid) or host:match(match_jid)
528 or (session.from_host and session.from_host:match(match_jid))
529 -- Pft! is what I say to list comprehensions
530 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
531 count_in = count_in + 1;
532 print(" "..host.." <- "..(session.from_host or "(unknown)")..(session.secure and " (encrypted)" or "")..(session.compressed and " (compressed)" or ""));
533 if session.type == "s2sin_unauthed" then
534 print(" Connection not yet authenticated");
536 for name in pairs(session.hosts) do
537 if name ~= session.from_host then
538 print(" also hosts "..tostring(name));
547 for session in pairs(incoming_s2s) do
548 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
549 count_in = count_in + 1;
550 print("Other incoming s2s connections");
551 print(" (unknown) <- "..(session.from_host or "(unknown)"));
555 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
558 function def_env.s2s:close(from, to)
559 local print, count = self.session.print, 0;
561 if not (from and to) then
562 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
563 elseif from == to then
564 return false, "Both from and to are the same... you can't do that :)";
567 if hosts[from] and not hosts[to] then
568 -- Is an outgoing connection
569 local session = hosts[from].s2sout[to];
571 print("No outgoing connection from "..from.." to "..to)
573 (session.close or s2smanager.destroy_session)(session);
575 print("Closed outgoing session from "..from.." to "..to);
577 elseif hosts[to] and not hosts[from] then
578 -- Is an incoming connection
579 for session in pairs(incoming_s2s) do
580 if session.to_host == to and session.from_host == from then
581 (session.close or s2smanager.destroy_session)(session);
587 print("No incoming connections from "..from.." to "..to);
589 print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
591 elseif hosts[to] and hosts[from] then
592 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
594 return false, "Neither of the hostnames you specified are being used on this server";
597 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
600 def_env.host = {}; def_env.hosts = def_env.host;
601 function def_env.host:activate(hostname, config)
602 local hostmanager_activate = require "core.hostmanager".activate;
603 if hosts[hostname] then
604 return false, "The host "..tostring(hostname).." is already activated";
607 local defined_hosts = config or configmanager.getconfig();
608 if not config and not defined_hosts[hostname] then
609 return false, "Couldn't find "..tostring(hostname).." defined in the config, perhaps you need to config:reload()?";
611 hostmanager_activate(hostname, config or defined_hosts[hostname]);
612 return true, "Host "..tostring(hostname).." activated";
615 function def_env.host:deactivate(hostname, reason)
616 local hostmanager_deactivate = require "core.hostmanager".deactivate;
617 local host = hosts[hostname];
619 return false, "The host "..tostring(hostname).." is not activated";
622 reason = { condition = "host-gone", text = reason };
624 hostmanager_deactivate(hostname, reason);
625 return true, "Host "..tostring(hostname).." deactivated";
628 function def_env.host:list()
629 local print = self.session.print;
631 for host in values(array.collect(keys(prosody.hosts)):sort()) do
635 return true, i.." hosts";
640 function printbanner(session)
641 local option = config.get("*", "core", "console_banner");
642 if option == nil or option == "full" or option == "graphic" then
645 | _ \ _ __ ___ ___ _-_ __| |_ _
646 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
647 | __/| | | (_) \__ \ |_| | (_| | |_| |
648 |_| |_| \___/|___/\___/ \__,_|\__, |
649 A study in simplicity |___/
653 if option == nil or option == "short" or option == "full" then
654 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
655 session.print("You may find more help on using this console in our online documentation at ");
656 session.print("http://prosody.im/doc/console\n");
658 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
659 if type(option) == "string" then
660 session.print(option)
661 elseif type(option) == "function" then
662 setfenv(option, redirect_output(_G, session));
663 pcall(option, session);
668 prosody.net_activate_ports("console", "console", {5582}, "tcp");