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 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 (...)
41 for i=1,select("#", ...) do
42 t[i] = tostring(select(i, ...));
44 w("| "..table.concat(t, "\t").."\n");
46 disconnect = function () conn:close(); end;
48 session.env = setmetatable({}, default_env_mt);
50 -- Load up environment with helper objects
51 for name, t in pairs(def_env) do
52 if type(t) == "table" then
53 session.env[name] = setmetatable({ session = session }, { __index = t });
62 function console_listener.onconnect(conn)
63 -- Handle new connection
64 local session = console:new_session(conn);
65 sessions[conn] = session;
67 session.send(string.char(0));
70 function console_listener.onincoming(conn, data)
71 local session = sessions[conn];
74 (function(session, data)
77 if data:match("^>") then
78 data = data:gsub("^>", "");
80 elseif data == "\004" then
81 commands["bye"](session, data);
84 local command = data:lower();
85 command = data:match("^%w+") or data:match("%p");
86 if commands[command] then
87 commands[command](session, data);
94 local chunkname = "=console";
95 local chunk, err = loadstring("return "..data, chunkname);
97 chunk, err = loadstring(data, chunkname);
99 err = err:gsub("^%[string .-%]:%d+: ", "");
100 err = err:gsub("^:%d+: ", "");
101 err = err:gsub("'<eof>'", "the end of the line");
102 session.print("Sorry, I couldn't understand that... "..err);
107 setfenv(chunk, (useglobalenv and redirect_output(_G, session)) or session.env or nil);
109 local ranok, taskok, message = pcall(chunk);
111 if not (ranok or message or useglobalenv) and commands[data:lower()] then
112 commands[data:lower()](session, data);
117 session.print("Fatal error while running command, it did not complete");
118 session.print("Error: "..taskok);
123 session.print("Result: "..tostring(taskok));
125 elseif (not taskok) and message then
126 session.print("Command completed with a problem");
127 session.print("Message: "..tostring(message));
131 session.print("OK: "..tostring(message));
134 session.send(string.char(0));
137 function console_listener.ondisconnect(conn, err)
138 local session = sessions[conn];
140 session.disconnect();
141 sessions[conn] = nil;
145 connlisteners_register('console', console_listener);
147 -- Console commands --
148 -- These are simple commands, not valid standalone in Lua
150 function commands.bye(session)
151 session.print("See you! :)");
152 session.disconnect();
154 commands.quit, commands.exit = commands.bye, commands.bye;
156 commands["!"] = function (session, data)
157 if data:match("^!!") then
158 session.print("!> "..session.env._);
159 return console_listener.onincoming(session.conn, session.env._);
161 local old, new = data:match("^!(.-[^\\])!(.-)!$");
163 local ok, res = pcall(string.gsub, session.env._, old, new);
168 session.print("!> "..res);
169 return console_listener.onincoming(session.conn, res);
171 session.print("Sorry, not sure what you want");
174 function commands.help(session, data)
175 local print = session.print;
176 local section = data:match("^help (%w+)");
178 print [[Commands are divided into multiple sections. For help on a particular section, ]]
179 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
181 print [[c2s - Commands to manage local client-to-server sessions]]
182 print [[s2s - Commands to manage sessions between this server and others]]
183 print [[module - Commands to load/reload/unload modules/plugins]]
184 print [[server - Uptime, version, shutting down, etc.]]
185 print [[config - Reloading the configuration, etc.]]
186 print [[console - Help regarding the console itself]]
187 elseif section == "c2s" then
188 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
189 print [[c2s:show_insecure() - Show all unencrypted client connections]]
190 print [[c2s:show_secure() - Show all encrypted client connections]]
191 print [[c2s:close(jid) - Close all sessions for the specified JID]]
192 elseif section == "s2s" then
193 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
194 print [[s2s:close(from, to) - Close a connection from one domain to another]]
195 elseif section == "module" then
196 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
197 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
198 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
199 print [[module:list(host) - List the modules loaded on the specified host]]
200 elseif section == "server" then
201 print [[server:version() - Show the server's version number]]
202 print [[server:uptime() - Show how long the server has been running]]
203 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
204 elseif section == "config" then
205 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
206 elseif section == "console" then
207 print [[Hey! Welcome to Prosody's admin console.]]
208 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
209 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
210 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
212 print [[For now we offer a couple of handy shortcuts:]]
213 print [[!! - Repeat the last command]]
214 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
216 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
217 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
218 print [[the running server. Great fun, but be careful not to break anything :)]]
223 -- Session environment --
224 -- Anything in def_env will be accessible within the session as a global variable
228 function def_env.server:insane_reload()
229 prosody.unlock_globals();
231 prosody = _G.prosody;
232 return true, "Server reloaded";
235 function def_env.server:version()
236 return true, tostring(prosody.version or "unknown");
239 function def_env.server:uptime()
240 local t = os.time()-prosody.start_time;
241 local seconds = t%60;
242 t = (t - seconds)/60;
243 local minutes = t%60;
244 t = (t - minutes)/60;
248 return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
249 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
250 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
253 function def_env.server:shutdown(reason)
254 prosody.shutdown(reason);
255 return true, "Shutdown initiated";
260 local function get_hosts_set(hosts, module)
261 if type(hosts) == "table" then
263 return set.new(hosts);
264 elseif hosts._items then
267 elseif type(hosts) == "string" then
268 return set.new { hosts };
269 elseif hosts == nil then
270 local mm = require "modulemanager";
271 return set.new(array.collect(keys(prosody.hosts)))
272 / function (host) return prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module); end;
276 function def_env.module:load(name, hosts, config)
277 local mm = require "modulemanager";
279 hosts = get_hosts_set(hosts);
281 -- Load the module for each host
282 local ok, err, count = true, nil, 0;
284 if (not mm.is_loaded(host, name)) then
285 ok, err = mm.load(host, name, config);
288 self.session.print(err or "Unknown error loading module");
291 self.session.print("Loaded for "..host);
296 return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
299 function def_env.module:unload(name, hosts)
300 local mm = require "modulemanager";
302 hosts = get_hosts_set(hosts, name);
304 -- Unload the module for each host
305 local ok, err, count = true, nil, 0;
307 if mm.is_loaded(host, name) then
308 ok, err = mm.unload(host, name);
311 self.session.print(err or "Unknown error unloading module");
314 self.session.print("Unloaded from "..host);
318 return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
321 function def_env.module:reload(name, hosts)
322 local mm = require "modulemanager";
324 hosts = get_hosts_set(hosts, name);
326 -- Reload the module for each host
327 local ok, err, count = true, nil, 0;
329 if mm.is_loaded(host, name) then
330 ok, err = mm.reload(host, name);
333 self.session.print(err or "Unknown error reloading module");
339 self.session.print("Reloaded on "..host);
343 return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
346 function def_env.module:list(hosts)
348 hosts = array.collect(keys(prosody.hosts));
350 if type(hosts) == "string" then
353 if type(hosts) ~= "table" then
354 return false, "Please supply a host or a list of hosts you would like to see";
357 local print = self.session.print;
358 for _, host in ipairs(hosts) do
360 local modules = array.collect(keys(prosody.hosts[host] and prosody.hosts[host].modules or {})):sort();
361 if #modules == 0 then
362 if prosody.hosts[host] then
363 print(" No modules loaded");
365 print(" Host not found");
368 for _, name in ipairs(modules) do
376 function def_env.config:load(filename, format)
377 local config_load = require "core.configmanager".load;
378 local ok, err = config_load(filename, format);
380 return false, err or "Unknown error loading config";
382 return true, "Config loaded";
385 function def_env.config:get(host, section, key)
386 local config_get = require "core.configmanager".get
387 return true, tostring(config_get(host, section, key));
390 function def_env.config:reload()
391 local ok, err = prosody.reload_config();
392 return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
396 function def_env.hosts:list()
397 for host, host_session in pairs(hosts) do
398 self.session.print(host);
403 function def_env.hosts:add(name)
408 local function show_c2s(callback)
409 for hostname, host in pairs(hosts) do
410 for username, user in pairs(host.sessions or {}) do
411 for resource, session in pairs(user.sessions or {}) do
412 local jid = username.."@"..hostname.."/"..resource;
413 callback(jid, session);
419 function def_env.c2s:show(match_jid)
420 local print, count = self.session.print, 0;
422 show_c2s(function (jid, session)
423 if curr_host ~= session.host then
424 curr_host = session.host;
427 if (not match_jid) or jid:match(match_jid) then
429 local status, priority = "unavailable", tostring(session.priority or "-");
430 if session.presence then
431 status = session.presence:child_with_name("show");
433 status = status:get_text() or "[invalid!]";
435 status = "available";
438 print(" "..jid.." - "..status.."("..priority..")");
441 return true, "Total: "..count.." clients";
444 function def_env.c2s:show_insecure(match_jid)
445 local print, count = self.session.print, 0;
446 show_c2s(function (jid, session)
447 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
452 return true, "Total: "..count.." insecure client connections";
455 function def_env.c2s:show_secure(match_jid)
456 local print, count = self.session.print, 0;
457 show_c2s(function (jid, session)
458 if ((not match_jid) or jid:match(match_jid)) and session.secure then
463 return true, "Total: "..count.." secure client connections";
466 function def_env.c2s:close(match_jid)
467 local print, count = self.session.print, 0;
468 show_c2s(function (jid, session)
469 if jid == match_jid or jid_bare(jid) == match_jid then
474 return true, "Total: "..count.." sessions closed";
478 function def_env.s2s:show(match_jid)
479 local _print = self.session.print;
480 local print = self.session.print;
482 local count_in, count_out = 0,0;
484 for host, host_session in pairs(hosts) do
485 print = function (...) _print(host); _print(...); print = _print; end
486 for remotehost, session in pairs(host_session.s2sout) do
487 if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
488 count_out = count_out + 1;
489 print(" "..host.." -> "..remotehost..(session.secure and " (encrypted)" or "")..(session.compressed and " (compressed)" or ""));
490 if session.sendq then
491 print(" There are "..#session.sendq.." queued outgoing stanzas for this connection");
493 if session.type == "s2sout_unauthed" then
494 if session.connecting then
495 print(" Connection not yet established");
496 if not session.srv_hosts then
497 if not session.conn then
498 print(" We do not yet have a DNS answer for this host's SRV records");
500 print(" This host has no SRV records, using A record instead");
502 elseif session.srv_choice then
503 print(" We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
504 local srv_choice = session.srv_hosts[session.srv_choice];
505 print(" Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
507 elseif session.notopen then
508 print(" The <stream> has not yet been opened");
509 elseif not session.dialback_key then
510 print(" Dialback has not been initiated yet");
511 elseif session.dialback_key then
512 print(" Dialback has been requested, but no result received");
517 local subhost_filter = function (h)
518 return (match_jid and h:match(match_jid));
520 for session in pairs(incoming_s2s) do
521 if session.to_host == host and ((not match_jid) or host:match(match_jid)
522 or (session.from_host and session.from_host:match(match_jid))
523 -- Pft! is what I say to list comprehensions
524 or (session.hosts and #array.collect(keys(session.hosts)):filter(subhost_filter)>0)) then
525 count_in = count_in + 1;
526 print(" "..host.." <- "..(session.from_host or "(unknown)")..(session.secure and " (encrypted)" or "")..(session.compressed and " (compressed)" or ""));
527 if session.type == "s2sin_unauthed" then
528 print(" Connection not yet authenticated");
530 for name in pairs(session.hosts) do
531 if name ~= session.from_host then
532 print(" also hosts "..tostring(name));
541 for session in pairs(incoming_s2s) do
542 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
543 count_in = count_in + 1;
544 print("Other incoming s2s connections");
545 print(" (unknown) <- "..(session.from_host or "(unknown)"));
549 return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
552 function def_env.s2s:close(from, to)
553 local print, count = self.session.print, 0;
555 if not (from and to) then
556 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
557 elseif from == to then
558 return false, "Both from and to are the same... you can't do that :)";
561 if hosts[from] and not hosts[to] then
562 -- Is an outgoing connection
563 local session = hosts[from].s2sout[to];
565 print("No outgoing connection from "..from.." to "..to)
567 (session.close or s2smanager.destroy_session)(session);
569 print("Closed outgoing session from "..from.." to "..to);
571 elseif hosts[to] and not hosts[from] then
572 -- Is an incoming connection
573 for session in pairs(incoming_s2s) do
574 if session.to_host == to and session.from_host == from then
575 (session.close or s2smanager.destroy_session)(session);
581 print("No incoming connections from "..from.." to "..to);
583 print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
585 elseif hosts[to] and hosts[from] then
586 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
588 return false, "Neither of the hostnames you specified are being used on this server";
591 return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
594 def_env.host = {}; def_env.hosts = def_env.host;
595 function def_env.host:activate(hostname, config)
596 local hostmanager_activate = require "core.hostmanager".activate;
597 if hosts[hostname] then
598 return false, "The host "..tostring(hostname).." is already activated";
601 local defined_hosts = config or configmanager.getconfig();
602 if not config and not defined_hosts[hostname] then
603 return false, "Couldn't find "..tostring(hostname).." defined in the config, perhaps you need to config:reload()?";
605 hostmanager_activate(hostname, config or defined_hosts[hostname]);
606 return true, "Host "..tostring(hostname).." activated";
609 function def_env.host:deactivate(hostname, reason)
610 local hostmanager_deactivate = require "core.hostmanager".deactivate;
611 local host = hosts[hostname];
613 return false, "The host "..tostring(hostname).." is not activated";
616 reason = { condition = "host-gone", text = reason };
618 hostmanager_deactivate(hostname, reason);
619 return true, "Host "..tostring(hostname).." deactivated";
622 function def_env.host:list()
623 local print = self.session.print;
625 for host in values(array.collect(keys(prosody.hosts)):sort()) do
629 return true, i.." hosts";
634 function printbanner(session)
635 local option = config.get("*", "core", "console_banner");
636 if option == nil or option == "full" or option == "graphic" then
639 | _ \ _ __ ___ ___ _-_ __| |_ _
640 | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
641 | __/| | | (_) \__ \ |_| | (_| | |_| |
642 |_| |_| \___/|___/\___/ \__,_|\__, |
643 A study in simplicity |___/
647 if option == nil or option == "short" or option == "full" then
648 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
649 session.print("You may find more help on using this console in our online documentation at ");
650 session.print("http://prosody.im/doc/console\n");
652 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
653 if type(option) == "string" then
654 session.print(option)
655 elseif type(option) == "function" then
656 setfenv(option, redirect_output(_G, session));
657 pcall(option, session);
662 prosody.net_activate_ports("console", "console", {5582}, "tcp");