b9d30716b929744ec56fe9a99c5e840faa0cc86a
[prosody.git] / plugins / mod_console.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 module.host = "*";
10
11 local _G = _G;
12
13 local prosody = _G.prosody;
14 local hosts = prosody.hosts;
15 local connlisteners_register = require "net.connlisteners".register;
16
17 local console_listener = { default_port = 5582; default_mode = "*l"; default_interface = "127.0.0.1" };
18
19 require "util.iterators";
20 local jid_bare = require "util.jid".bare;
21 local set, array = require "util.set", require "util.array";
22
23 local commands = {};
24 local def_env = {};
25 local default_env_mt = { __index = def_env };
26
27 prosody.console = { commands = commands, env = def_env };
28
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 });
31 end
32
33 console = {};
34
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;
41                         };
42         session.env = setmetatable({}, default_env_mt);
43         
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 });
48                 end
49         end
50         
51         return session;
52 end
53
54 local sessions = {};
55
56 function console_listener.listener(conn, data)
57         local session = sessions[conn];
58         
59         if not session then
60                 -- Handle new connection
61                 session = console:new_session(conn);
62                 sessions[conn] = session;
63                 printbanner(session);
64         end
65         if data then
66                 -- Handle data
67                 (function(session, data)
68                         local useglobalenv;
69                         
70                         if data:match("^>") then
71                                 data = data:gsub("^>", "");
72                                 useglobalenv = true;
73                         else
74                                 local command = data:lower();
75                                 command = data:match("^%w+") or data:match("%p");
76                                 if commands[command] then
77                                         commands[command](session, data);
78                                         return;
79                                 end
80                         end
81
82                         session.env._ = data;
83                         
84                         local chunk, err = loadstring("return "..data);
85                         if not chunk then
86                                 chunk, err = loadstring(data);
87                                 if not chunk then
88                                         err = err:gsub("^%[string .-%]:%d+: ", "");
89                                         err = err:gsub("^:%d+: ", "");
90                                         err = err:gsub("'<eof>'", "the end of the line");
91                                         session.print("Sorry, I couldn't understand that... "..err);
92                                         return;
93                                 end
94                         end
95                         
96                         setfenv(chunk, (useglobalenv and redirect_output(_G, session)) or session.env or nil);
97                         
98                         local ranok, taskok, message = pcall(chunk);
99                         
100                         if not (ranok or message or useglobalenv) and commands[data:lower()] then
101                                 commands[data:lower()](session, data);
102                                 return;
103                         end
104                         
105                         if not ranok then
106                                 session.print("Fatal error while running command, it did not complete");
107                                 session.print("Error: "..taskok);
108                                 return;
109                         end
110                         
111                         if not message then
112                                 session.print("Result: "..tostring(taskok));
113                                 return;
114                         elseif (not taskok) and message then
115                                 session.print("Command completed with a problem");
116                                 session.print("Message: "..tostring(message));
117                                 return;
118                         end
119                         
120                         session.print("OK: "..tostring(message));
121                 end)(session, data);
122         end
123         session.send(string.char(0));
124 end
125
126 function console_listener.disconnect(conn, err)
127         
128 end
129
130 connlisteners_register('console', console_listener);
131
132 -- Console commands --
133 -- These are simple commands, not valid standalone in Lua
134
135 function commands.bye(session)
136         session.print("See you! :)");
137         session.disconnect();
138 end
139 commands.quit, commands.exit = commands.bye, commands.bye;
140
141 commands["!"] = function (session, data)
142         if data:match("^!!") then
143                 session.print("!> "..session.env._);
144                 return console_listener.listener(session.conn, session.env._);
145         end
146         local old, new = data:match("^!(.-[^\\])!(.-)!$");
147         if old and new then
148                 local ok, res = pcall(string.gsub, session.env._, old, new);
149                 if not ok then
150                         session.print(res)
151                         return;
152                 end
153                 session.print("!> "..res);
154                 return console_listener.listener(session.conn, res);
155         end
156         session.print("Sorry, not sure what you want");
157 end
158
159 function commands.help(session, data)
160         local print = session.print;
161         local section = data:match("^help (%w+)");
162         if not section then
163                 print [[Commands are divided into multiple sections. For help on a particular section, ]]
164                 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
165                 print [[]]
166                 print [[c2s - Commands to manage local client-to-server sessions]]
167                 print [[s2s - Commands to manage sessions between this server and others]]
168                 print [[module - Commands to load/reload/unload modules/plugins]]
169                 print [[server - Uptime, version, shutting down, etc.]]
170                 print [[console - Help regarding the console itself]]
171         elseif section == "c2s" then
172                 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
173                 print [[c2s:show_insecure() - Show all unencrypted client connections]]
174                 print [[c2s:show_secure() - Show all encrypted client connections]]
175                 print [[c2s:close(jid) - Close all sessions for the specified JID]]
176         elseif section == "s2s" then
177                 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
178                 print [[s2s:close(from, to) - Close a connection from one domain to another]]
179         elseif section == "module" then
180                 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
181                 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
182                 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
183                 print [[module:list(host) - List the modules loaded on the specified host]]
184         elseif section == "server" then
185                 print [[server:version() - Show the server's version number]]
186                 print [[server:uptime() - Show how long the server has been running]]
187                 --print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
188         elseif section == "console" then
189                 print [[Hey! Welcome to Prosody's admin console.]]
190                 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
191                 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
192                 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
193                 print [[]]
194                 print [[For now we offer a couple of handy shortcuts:]]
195                 print [[!! - Repeat the last command]]
196                 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
197                 print [[]]
198                 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
199                 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
200                 print [[the running server. Great fun, but be careful not to break anything :)]]
201         end
202         print [[]]
203 end
204
205 -- Session environment --
206 -- Anything in def_env will be accessible within the session as a global variable
207
208 def_env.server = {};
209 function def_env.server:reload()
210         prosody.unlock_globals();
211         dofile "prosody"
212         prosody = _G.prosody;
213         return true, "Server reloaded";
214 end
215
216 function def_env.server:version()
217         return true, tostring(prosody.version or "unknown");
218 end
219
220 function def_env.server:uptime()
221         local t = os.time()-prosody.start_time;
222         local seconds = t%60;
223         t = (t - seconds)/60;
224         local minutes = t%60;
225         t = (t - minutes)/60;
226         local hours = t%24;
227         t = (t - hours)/24;
228         local days = t;
229         return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)", 
230                 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "", 
231                 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
232 end
233
234 def_env.module = {};
235
236 local function get_hosts_set(hosts, module)
237         if type(hosts) == "table" then
238                 if hosts[1] then
239                         return set.new(hosts);
240                 elseif hosts._items then
241                         return hosts;
242                 end
243         elseif type(hosts) == "string" then
244                 return set.new { hosts };
245         elseif hosts == nil then
246                 local mm = require "modulemanager";
247                 return set.new(array.collect(keys(prosody.hosts)))
248                         / function (host) return prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module); end;
249         end
250 end
251
252 function def_env.module:load(name, hosts, config)
253         local mm = require "modulemanager";
254         
255         hosts = get_hosts_set(hosts);
256         
257         -- Load the module for each host
258         local ok, err, count = true, nil, 0;
259         for host in hosts do
260                 if (not mm.is_loaded(host, name)) then
261                         ok, err = mm.load(host, name, config);
262                         if not ok then
263                                 ok = false;
264                                 self.session.print(err or "Unknown error loading module");
265                         else
266                                 count = count + 1;
267                                 self.session.print("Loaded for "..host);
268                         end
269                 end
270         end
271         
272         return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));       
273 end
274
275 function def_env.module:unload(name, hosts)
276         local mm = require "modulemanager";
277
278         hosts = get_hosts_set(hosts, name);
279         
280         -- Unload the module for each host
281         local ok, err, count = true, nil, 0;
282         for host in hosts do
283                 if mm.is_loaded(host, name) then
284                         ok, err = mm.unload(host, name);
285                         if not ok then
286                                 ok = false;
287                                 self.session.print(err or "Unknown error unloading module");
288                         else
289                                 count = count + 1;
290                                 self.session.print("Unloaded from "..host);
291                         end
292                 end
293         end
294         return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
295 end
296
297 function def_env.module:reload(name, hosts)
298         local mm = require "modulemanager";
299
300         hosts = get_hosts_set(hosts, name);
301         
302         -- Reload the module for each host
303         local ok, err, count = true, nil, 0;
304         for host in hosts do
305                 if mm.is_loaded(host, name) then
306                         ok, err = mm.reload(host, name);
307                         if not ok then
308                                 ok = false;
309                                 self.session.print(err or "Unknown error reloading module");
310                         else
311                                 count = count + 1;
312                                 if ok == nil then
313                                         ok = true;
314                                 end
315                                 self.session.print("Reloaded on "..host);
316                         end
317                 end
318         end
319         return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
320 end
321
322 function def_env.module:list(hosts)
323         if hosts == nil then
324                 hosts = array.collect(keys(prosody.hosts));
325         end
326         if type(hosts) == "string" then
327                 hosts = { hosts };
328         end
329         if type(hosts) ~= "table" then
330                 return false, "Please supply a host or a list of hosts you would like to see";
331         end
332         
333         local print = self.session.print;
334         for _, host in ipairs(hosts) do
335                 print(host..":");
336                 local modules = array.collect(keys(prosody.hosts[host].modules or {})):sort();
337                 if #modules == 0 then
338                         print("    No modules loaded");
339                 else
340                         for _, name in ipairs(modules) do
341                                 print("    "..name);
342                         end
343                 end
344         end
345 end
346
347 def_env.config = {};
348 function def_env.config:load(filename, format)
349         local config_load = require "core.configmanager".load;
350         local ok, err = config_load(filename, format);
351         if not ok then
352                 return false, err or "Unknown error loading config";
353         end
354         return true, "Config loaded";
355 end
356
357 function def_env.config:get(host, section, key)
358         local config_get = require "core.configmanager".get
359         return true, tostring(config_get(host, section, key));
360 end
361
362 def_env.hosts = {};
363 function def_env.hosts:list()
364         for host, host_session in pairs(hosts) do
365                 self.session.print(host);
366         end
367         return true, "Done";
368 end
369
370 function def_env.hosts:add(name)
371 end
372
373 def_env.c2s = {};
374
375 local function show_c2s(callback)
376         for hostname, host in pairs(hosts) do
377                 for username, user in pairs(host.sessions or {}) do
378                         for resource, session in pairs(user.sessions or {}) do
379                                 local jid = username.."@"..hostname.."/"..resource;
380                                 callback(jid, session);
381                         end
382                 end
383         end
384 end
385
386 function def_env.c2s:show(match_jid)
387         local print, count = self.session.print, 0;
388         show_c2s(function (jid, session)
389                 if (not match_jid) or jid:match(match_jid) then
390                         count = count + 1;
391                         local status, priority = "unavailable", tostring(session.priority or "-");
392                         if session.presence then
393                                 status = session.presence:child_with_name("show");
394                                 if status then
395                                         status = status:get_text() or "[invalid!]";
396                                 else
397                                         status = "available";
398                                 end
399                         end
400                         print(jid.." - "..status.."("..priority..")");
401                 end             
402         end);
403         return true, "Total: "..count.." clients";
404 end
405
406 function def_env.c2s:show_insecure(match_jid)
407         local print, count = self.session.print, 0;
408         show_c2s(function (jid, session)
409                 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
410                         count = count + 1;
411                         print(jid);
412                 end             
413         end);
414         return true, "Total: "..count.." insecure client connections";
415 end
416
417 function def_env.c2s:show_secure(match_jid)
418         local print, count = self.session.print, 0;
419         show_c2s(function (jid, session)
420                 if ((not match_jid) or jid:match(match_jid)) and session.secure then
421                         count = count + 1;
422                         print(jid);
423                 end             
424         end);
425         return true, "Total: "..count.." secure client connections";
426 end
427
428 function def_env.c2s:close(match_jid)
429         local print, count = self.session.print, 0;
430         show_c2s(function (jid, session)
431                 if jid == match_jid or jid_bare(jid) == match_jid then
432                         count = count + 1;
433                         session:close();
434                 end
435         end);
436         return true, "Total: "..count.." sessions closed";
437 end
438
439 def_env.s2s = {};
440 function def_env.s2s:show(match_jid)
441         local _print = self.session.print;
442         local print = self.session.print;
443         
444         local count_in, count_out = 0,0;
445         
446         for host, host_session in pairs(hosts) do
447                 print = function (...) _print(host); _print(...); print = _print; end
448                 for remotehost, session in pairs(host_session.s2sout) do
449                         if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
450                                 count_out = count_out + 1;
451                                 print("    "..host.." -> "..remotehost);
452                                 if session.sendq then
453                                         print("        There are "..#session.sendq.." queued outgoing stanzas for this connection");
454                                 end
455                                 if session.type == "s2sout_unauthed" then
456                                         if session.connecting then
457                                                 print("        Connection not yet established");
458                                                 if not session.srv_hosts then
459                                                         if not session.conn then
460                                                                 print("        We do not yet have a DNS answer for this host's SRV records");
461                                                         else
462                                                                 print("        This host has no SRV records, using A record instead");
463                                                         end
464                                                 elseif session.srv_choice then
465                                                         print("        We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
466                                                         local srv_choice = session.srv_hosts[session.srv_choice];
467                                                         print("        Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
468                                                 end
469                                         elseif session.notopen then
470                                                 print("        The <stream> has not yet been opened");
471                                         elseif not session.dialback_key then
472                                                 print("        Dialback has not been initiated yet");
473                                         elseif session.dialback_key then
474                                                 print("        Dialback has been requested, but no result received");
475                                         end
476                                 end
477                         end
478                 end     
479                 
480                 for session in pairs(incoming_s2s) do
481                         if session.to_host == host and ((not match_jid) or host:match(match_jid) 
482                                 or (session.from_host and session.from_host:match(match_jid))) then
483                                 count_in = count_in + 1;
484                                 print("    "..host.." <- "..(session.from_host or "(unknown)"));
485                                 if session.type == "s2sin_unauthed" then
486                                                 print("        Connection not yet authenticated");
487                                 end
488                                 for name in pairs(session.hosts) do
489                                         if name ~= session.from_host then
490                                                 print("        also hosts "..tostring(name));
491                                         end
492                                 end
493                         end
494                 end
495                 
496                 print = _print;
497         end
498         
499         for session in pairs(incoming_s2s) do
500                 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
501                         count_in = count_in + 1;
502                         print("Other incoming s2s connections");
503                         print("    (unknown) <- "..(session.from_host or "(unknown)"));                 
504                 end
505         end
506         
507         return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
508 end
509
510 function def_env.s2s:close(from, to)
511         local print, count = self.session.print, 0;
512         
513         if not (from and to) then
514                 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
515         elseif from == to then
516                 return false, "Both from and to are the same... you can't do that :)";
517         end
518         
519         if hosts[from] and not hosts[to] then
520                 -- Is an outgoing connection
521                 local session = hosts[from].s2sout[to];
522                 if not session then 
523                         print("No outgoing connection from "..from.." to "..to)
524                 else
525                         (session.close or s2smanager.destroy_session)(session);
526                         count = count + 1;
527                         print("Closed outgoing session from "..from.." to "..to);
528                 end
529         elseif hosts[to] and not hosts[from] then
530                 -- Is an incoming connection
531                 for session in pairs(incoming_s2s) do
532                         if session.to_host == to and session.from_host == from then
533                                 (session.close or s2smanager.destroy_session)(session);
534                                 count = count + 1;
535                         end
536                 end
537                 
538                 if count == 0 then
539                         print("No incoming connections from "..from.." to "..to);
540                 else
541                         print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
542                 end
543         elseif hosts[to] and hosts[from] then
544                 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
545         else
546                 return false, "Neither of the hostnames you specified are being used on this server";
547         end
548         
549         return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
550 end
551
552 -------------
553
554 function printbanner(session)
555         local option = config.get("*", "core", "console_banner");
556 if option == nil or option == "full" or option == "graphic" then
557 session.print [[
558                    ____                \   /     _       
559                     |  _ \ _ __ ___  ___  _-_   __| |_   _ 
560                     | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
561                     |  __/| | | (_) \__ \ |_| | (_| | |_| |
562                     |_|   |_|  \___/|___/\___/ \__,_|\__, |
563                     A study in simplicity            |___/ 
564
565 ]]
566 end
567 if option == nil or option == "short" or option == "full" then
568 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
569 session.print("You may find more help on using this console in our online documentation at ");
570 session.print("http://prosody.im/doc/console\n");
571 end
572 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
573         if type(option) == "string" then
574                 session.print(option)
575         elseif type(option) == "function" then
576                 setfenv(option, redirect_output(_G, session));
577                 pcall(option, session);
578         end
579 end
580 end