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