2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 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 return setmetatable({ print = session.print }, { __index = function (t, k) return rawget(_G, k); end, __newindex = function (t, k, v) rawset(_G, k, v); end });
35 function console:new_session(conn)
36 local w = function(s) conn:write(s:gsub("\n", "\r\n")); end;
37 local session = { conn = conn;
38 send = function (t) w(tostring(t)); end;
39 print = function (t) w("| "..tostring(t).."\n"); end;
40 disconnect = function () conn:close(); end;
42 session.env = setmetatable({}, default_env_mt);
44 -- Load up environment with helper objects
45 for name, t in pairs(def_env) do
46 if type(t) == "table" then
47 session.env[name] = setmetatable({ session = session }, { __index = t });
56 function console_listener.onincoming(conn, data)
57 local session = sessions[conn];
60 -- Handle new connection
61 session = console:new_session(conn);
62 sessions[conn] = session;
67 (function(session, data)
70 if data:match("^>") then
71 data = data:gsub("^>", "");
73 elseif data == "\004" then
74 commands["bye"](session, data);
77 local command = data:lower();
78 command = data:match("^%w+") or data:match("%p");
79 if commands[command] then
80 commands[command](session, data);
87 local chunk, err = loadstring("return "..data);
89 chunk, err = loadstring(data);
91 err = err:gsub("^%[string .-%]:%d+: ", "");
92 err = err:gsub("^:%d+: ", "");
93 err = err:gsub("'<eof>'", "the end of the line");
94 session.print("Sorry, I couldn't understand that... "..err);
99 setfenv(chunk, (useglobalenv and redirect_output(_G, session)) or session.env or nil);
101 local ranok, taskok, message = pcall(chunk);
103 if not (ranok or message or useglobalenv) and commands[data:lower()] then
104 commands[data:lower()](session, data);
109 session.print("Fatal error while running command, it did not complete");
110 session.print("Error: "..taskok);
115 session.print("Result: "..tostring(taskok));
117 elseif (not taskok) and message then
118 session.print("Command completed with a problem");
119 session.print("Message: "..tostring(message));
123 session.print("OK: "..tostring(message));
126 session.send(string.char(0));
129 function console_listener.ondisconnect(conn, err)
130 local session = sessions[conn];
132 session.disconnect();
133 sessions[conn] = nil;
137 connlisteners_register('console', console_listener);
139 -- Console commands --
140 -- These are simple commands, not valid standalone in Lua
142 function commands.bye(session)
143 session.print("See you! :)");
144 session.disconnect();
146 commands.quit, commands.exit = commands.bye, commands.bye;
148 commands["!"] = function (session, data)
149 if data:match("^!!") then
150 session.print("!> "..session.env._);
151 return console_listener.onincoming(session.conn, session.env._);
153 local old, new = data:match("^!(.-[^\\])!(.-)!$");
155 local ok, res = pcall(string.gsub, session.env._, old, new);
160 session.print("!> "..res);
161 return console_listener.onincoming(session.conn, res);
163 session.print("Sorry, not sure what you want");
166 function commands.help(session, data)
167 local print = session.print;
168 local section = data:match("^help (%w+)");
170 print [[Commands are divided into multiple sections. For help on a particular section, ]]
171 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
173 print [[c2s - Commands to manage local client-to-server sessions]]
174 print [[s2s - Commands to manage sessions between this server and others]]
175 print [[module - Commands to load/reload/unload modules/plugins]]
176 print [[server - Uptime, version, shutting down, etc.]]
177 print [[config - Reloading the configuration, etc.]]
178 print [[console - Help regarding the console itself]]
179 elseif section == "c2s" then
180 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
181 print [[c2s:show_insecure() - Show all unencrypted client connections]]
182 print [[c2s:show_secure() - Show all encrypted client connections]]
183 print [[c2s:close(jid) - Close all sessions for the specified JID]]
184 elseif section == "s2s" then
185 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
186 print [[s2s:close(from, to) - Close a connection from one domain to another]]
187 elseif section == "module" then
188 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
189 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
190 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
191 print [[module:list(host) - List the modules loaded on the specified host]]
192 elseif section == "server" then
193 print [[server:version() - Show the server's version number]]
194 print [[server:uptime() - Show how long the server has been running]]
195 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
196 elseif section == "config" then
197 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
198 elseif section == "console" then
199 print [[Hey! Welcome to Prosody's admin console.]]
200 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
201 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
202 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
204 print [[For now we offer a couple of handy shortcuts:]]
205 print [[!! - Repeat the last command]]
206 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
208 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
209 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
210 print [[the running server. Great fun, but be careful not to break anything :)]]
215 -- Session environment --
216 -- Anything in def_env will be accessible within the session as a global variable
220 function def_env.server:insane_reload()
221 prosody.unlock_globals();
223 prosody = _G.prosody;
224 return true, "Server reloaded";
227 function def_env.server:version()
228 return true, tostring(prosody.version or "unknown");
231 function def_env.server:uptime()
232 local t = os.time()-prosody.start_time;
233 local seconds = t%60;
234 t = (t - seconds)/60;
235 local minutes = t%60;
236 t = (t - minutes)/60;
240 return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
241 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
242 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
245 function def_env.server:shutdown(reason)
246 prosody.shutdown(reason);
247 return true, "Shutdown initiated";
252 local function get_hosts_set(hosts, module)
253 if type(hosts) == "table" then
255 return set.new(hosts);
256 elseif hosts._items then
259 elseif type(hosts) == "string" then
260 return set.new { hosts };
261 elseif hosts == nil then
262 local mm = require "modulemanager";
263 return set.new(array.collect(keys(prosody.hosts)))
264 / function (host) return prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module); end;
268 function def_env.module:load(name, hosts, config)
269 local mm = require "modulemanager";
271 hosts = get_hosts_set(hosts);
273 -- Load the module for each host
274 local ok, err, count = true, nil, 0;
276 if (not mm.is_loaded(host, name)) then
277 ok, err = mm.load(host, name, config);
280 self.session.print(err or "Unknown error loading module");
283 self.session.print("Loaded for "..host);
288 return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
291 function def_env.module:unload(name, hosts)
292 local mm = require "modulemanager";
294 hosts = get_hosts_set(hosts, name);
296 -- Unload the module for each host
297 local ok, err, count = true, nil, 0;
299 if mm.is_loaded(host, name) then
300 ok, err = mm.unload(host, name);
303 self.session.print(err or "Unknown error unloading module");
306 self.session.print("Unloaded from "..host);
310 return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
313 function def_env.module:reload(name, hosts)
314 local mm = require "modulemanager";
316 hosts = get_hosts_set(hosts, name);
318 -- Reload the module for each host
319 local ok, err, count = true, nil, 0;
321 if mm.is_loaded(host, name) then
322 ok, err = mm.reload(host, name);
325 self.session.print(err or "Unknown error reloading module");
331 self.session.print("Reloaded on "..host);
335 return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
338 function def_env.module:list(hosts)
340 hosts = array.collect(keys(prosody.hosts));
342 if type(hosts) == "string" then
345 if type(hosts) ~= "table" then
346 return false, "Please supply a host or a list of hosts you would like to see";
349 local print = self.session.print;
350 for _, host in ipairs(hosts) do
352 local modules = array.collect(keys(prosody.hosts[host] and prosody.hosts[host].modules or {})):sort();
353 if #modules == 0 then
354 if prosody.hosts[host] then
355 print(" No modules loaded");
357 print(" Host not found");
360 for _, name in ipairs(modules) do
368 function def_env.config:load(filename, format)
369 local config_load = require "core.configmanager".load;
370 local ok, err = config_load(filename, format);
372 return false, err or "Unknown error loading config";
374 return true, "Config loaded";
377 function def_env.config:get(host, section, key)
378 local config_get = require "core.configmanager".get
379 return true, tostring(config_get(host, section, key));
382 function def_env.config:reload()
383 local ok, err = prosody.reload_config();
384 return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
388 function def_env.hosts:list()
389 for host, host_session in pairs(hosts) do
390 self.session.print(host);
395 function def_env.hosts:add(name)
400 local function show_c2s(callback)
401 for hostname, host in pairs(hosts) do
402 for username, user in pairs(host.sessions or {}) do
403 for resource, session in pairs(user.sessions or {}) do
404 local jid = username.."@"..hostname.."/"..resource;
405 callback(jid, session);
411 function def_env.c2s:show(match_jid)
412 local print, count = self.session.print, 0;
414 show_c2s(function (jid, session)
415 if curr_host ~= session.host then
416 curr_host = session.host;
419 if (not match_jid) or jid:match(match_jid) then
421 local status, priority = "unavailable", tostring(session.priority or "-");
422 if session.presence then
423 status = session.presence:child_with_name("show");
425 status = status:get_text() or "[invalid!]";
427 status = "available";
430 print(" "..jid.." - "..status.."("..priority..")");
433 return true, "Total: "..count.." clients";
436 function def_env.c2s:show_insecure(match_jid)
437 local print, count = self.session.print, 0;
438 show_c2s(function (jid, session)
439 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
444 return true, "Total: "..count.." insecure client connections";
447 function def_env.c2s:show_secure(match_jid)
448 local print, count = self.session.print, 0;
449 show_c2s(function (jid, session)
450 if ((not match_jid) or jid:match(match_jid)) and session.secure then
455 return true, "Total: "..count.." secure client connections";
458 function def_env.c2s:close(match_jid)
459 local print, count = self.session.print, 0;
460 show_c2s(function (jid, session)
461 if jid == match_jid or jid_bare(jid) == match_jid then
466 return true, "Total: "..count.." sessions closed";
470 function def_env.s2s:show(match_jid)
471 local _print = self.session.print;
472 local print = self.session.print;
474 local count_in, count_out = 0,0;
476 for host, host_session in pairs(hosts) do
477 print = function (...) _print(host); _print(...); print = _print; end
478 for remotehost, session in pairs(host_session.s2sout) do
479 if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
480 count_out = count_out + 1;
481 print(" "..host.." -> "..remotehost..(session.secure and " (encrypted)" or "")..(session.compressed and " (compressed)" or ""));
482 if session.sendq then
483 print(" There are "..#session.sendq.." queued outgoing stanzas for this connection");
485 if session.type == "s2sout_unauthed" then
486 if session.connecting then
487 print(" Connection not yet established");
488 if not session.srv_hosts then
489 if not session.conn then
490 print(" We do not yet have a DNS answer for this host's SRV records");
492 print(" This host has no SRV records, using A record instead");
494 elseif session.srv_choice then
495 print(" We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
496 local srv_choice = session.srv_hosts[session.srv_choice];
497 print(" Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
499 elseif session.notopen then
500 print(" The <stream> has not yet been opened");
501 elseif not session.dialback_key then
502 print(" Dialback has not been initiated yet");
503 elseif session.dialback_key then
504 print(" Dialback has been requested, but no result received");
509 local subhost_filter = function (h)
510 return (match_jid and h:match(match_jid));
512 for session in pairs(incoming_s2s) do
513 if session.to_host == host and ((not match_jid) or host:match(match_jid)
514 or (session.from_host and session.from_host:match(match_jid))
515 -- Pft! is what I say to list comprehensions
516 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
517 count_in = count_in + 1;
518 print(" "..host.." <- "..(session.from_host or "(unknown)")..(session.secure and " (encrypted)" or "")..(session.compressed and " (compressed)" or ""));
519 if session.type == "s2sin_unauthed" then
520 print(" Connection not yet authenticated");
522 for name in pairs(session.hosts) do
523 if name ~= session.from_host then
524 print(" also hosts "..tostring(name));
533 for session in pairs(incoming_s2s) do
534 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
535 count_in = count_in + 1;
536 print("Other incoming s2s connections");
537 print(" (unknown) <- "..(session.from_host or "(unknown)"));
541 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
544 function def_env.s2s:close(from, to)
545 local print, count = self.session.print, 0;
547 if not (from and to) then
548 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
549 elseif from == to then
550 return false, "Both from and to are the same... you can't do that :)";
553 if hosts[from] and not hosts[to] then
554 -- Is an outgoing connection
555 local session = hosts[from].s2sout[to];
557 print("No outgoing connection from "..from.." to "..to)
559 (session.close or s2smanager.destroy_session)(session);
561 print("Closed outgoing session from "..from.." to "..to);
563 elseif hosts[to] and not hosts[from] then
564 -- Is an incoming connection
565 for session in pairs(incoming_s2s) do
566 if session.to_host == to and session.from_host == from then
567 (session.close or s2smanager.destroy_session)(session);
573 print("No incoming connections from "..from.." to "..to);
575 print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
577 elseif hosts[to] and hosts[from] then
578 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
580 return false, "Neither of the hostnames you specified are being used on this server";
583 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
586 def_env.host = {}; def_env.hosts = def_env.host;
587 function def_env.host:activate(hostname, config)
588 local hostmanager_activate = require "core.hostmanager".activate;
589 if hosts[hostname] then
590 return false, "The host "..tostring(hostname).." is already activated";
593 local defined_hosts = config or configmanager.getconfig();
594 if not config and not defined_hosts[hostname] then
595 return false, "Couldn't find "..tostring(hostname).." defined in the config, perhaps you need to config:reload()?";
597 hostmanager_activate(hostname, config or defined_hosts[hostname]);
598 return true, "Host "..tostring(hostname).." activated";
601 function def_env.host:deactivate(hostname, reason)
602 local hostmanager_deactivate = require "core.hostmanager".deactivate;
603 local host = hosts[hostname];
605 return false, "The host "..tostring(hostname).." is not activated";
608 reason = { condition = "host-gone", text = reason };
610 hostmanager_deactivate(hostname, reason);
611 return true, "Host "..tostring(hostname).." deactivated";
614 function def_env.host:list()
615 local print = self.session.print;
617 for host in values(array.collect(keys(prosody.hosts)):sort()) do
621 return true, i.." hosts";
626 function printbanner(session)
627 local option = config.get("*", "core", "console_banner");
628 if option == nil or option == "full" or option == "graphic" then
631 | _ \ _ __ ___ ___ _-_ __| |_ _
632 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
633 | __/| | | (_) \__ \ |_| | (_| | |_| |
634 |_| |_| \___/|___/\___/ \__,_|\__, |
635 A study in simplicity |___/
639 if option == nil or option == "short" or option == "full" then
640 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
641 session.print("You may find more help on using this console in our online documentation at ");
642 session.print("http://prosody.im/doc/console\n");
644 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
645 if type(option) == "string" then
646 session.print(option)
647 elseif type(option) == "function" then
648 setfenv(option, redirect_output(_G, session));
649 pcall(option, session);
654 prosody.net_activate_ports("console", "console", {5582}, "tcp");