9d47cbc685f2cd1f1f27785647da2a23bb972bfa
[prosody.git] / plugins / mod_console.lua
1 -- Prosody IM v0.4
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"; };
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 local function redirect_output(_G, session)
28         return setmetatable({ print = session.print }, { __index = function (t, k) return rawget(_G, k); end, __newindex = function (t, k, v) rawset(_G, k, v); end });
29 end
30
31 console = {};
32
33 function console:new_session(conn)
34         local w = function(s) conn.write(s:gsub("\n", "\r\n")); end;
35         local session = { conn = conn;
36                         send = function (t) w(tostring(t)); end;
37                         print = function (t) w("| "..tostring(t).."\n"); end;
38                         disconnect = function () conn.close(); end;
39                         };
40         session.env = setmetatable({}, default_env_mt);
41         
42         -- Load up environment with helper objects
43         for name, t in pairs(def_env) do
44                 if type(t) == "table" then
45                         session.env[name] = setmetatable({ session = session }, { __index = t });
46                 end
47         end
48         
49         return session;
50 end
51
52 local sessions = {};
53
54 function console_listener.listener(conn, data)
55         local session = sessions[conn];
56         
57         if not session then
58                 -- Handle new connection
59                 session = console:new_session(conn);
60                 sessions[conn] = session;
61                 printbanner(session);
62         end
63         if data then
64                 -- Handle data
65                 (function(session, data)
66                         local useglobalenv;
67                         
68                         if data:match("[!.]$") then
69                                 local command = data:lower();
70                                 command = data:match("^%w+") or data:match("%p");
71                                 if commands[command] then
72                                         commands[command](session, data);
73                                         return;
74                                 end
75                         end
76
77                         if data:match("^>") then
78                                 data = data:gsub("^>", "");
79                                 useglobalenv = true;
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 then
101                                 session.print("Fatal error while running command, it did not complete");
102                                 session.print("Error: "..taskok);
103                                 return;
104                         end
105                         
106                         if not message then
107                                 session.print("Result: "..tostring(taskok));
108                                 return;
109                         elseif (not taskok) and message then
110                                 session.print("Command completed with a problem");
111                                 session.print("Message: "..tostring(message));
112                                 return;
113                         end
114                         
115                         session.print("OK: "..tostring(message));
116                 end)(session, data);
117         end
118         session.send(string.char(0));
119 end
120
121 function console_listener.disconnect(conn, err)
122         
123 end
124
125 connlisteners_register('console', console_listener);
126
127 -- Console commands --
128 -- These are simple commands, not valid standalone in Lua
129
130 function commands.bye(session)
131         session.print("See you! :)");
132         session.disconnect();
133 end
134
135 commands["!"] = function (session, data)
136         if data:match("^!!") then
137                 session.print("!> "..session.env._);
138                 return console_listener.listener(session.conn, session.env._);
139         end
140         local old, new = data:match("^!(.-[^\\])!(.-)!$");
141         if old and new then
142                 local ok, res = pcall(string.gsub, session.env._, old, new);
143                 if not ok then
144                         session.print(res)
145                         return;
146                 end
147                 session.print("!> "..res);
148                 return console_listener.listener(session.conn, res);
149         end
150         session.print("Sorry, not sure what you want");
151 end
152
153 -- Session environment --
154 -- Anything in def_env will be accessible within the session as a global variable
155
156 def_env.server = {};
157 function def_env.server:reload()
158         prosody.unlock_globals();
159         dofile "prosody"
160         prosody = _G.prosody;
161         return true, "Server reloaded";
162 end
163
164 def_env.module = {};
165
166 local function get_hosts_set(hosts, module)
167         if type(hosts) == "table" then
168                 if hosts[1] then
169                         return set.new(hosts);
170                 elseif hosts._items then
171                         return hosts;
172                 end
173         elseif type(hosts) == "string" then
174                 return set.new { hosts };
175         elseif hosts == nil then
176                 local mm = require "modulemanager";
177                 return set.new(array.collect(keys(prosody.hosts)))
178                         / function (host) return prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module); end;
179         end
180 end
181
182 function def_env.module:load(name, hosts, config)
183         local mm = require "modulemanager";
184         
185         hosts = get_hosts_set(hosts);
186         
187         -- Load the module for each host
188         local ok, err, count = true, nil, 0;
189         for host in hosts do
190                 if (not mm.is_loaded(host, name)) then
191                         ok, err = mm.load(host, name, config);
192                         if not ok then
193                                 ok = false;
194                                 self.session.print(err or "Unknown error loading module");
195                         else
196                                 count = count + 1;
197                                 self.session.print("Loaded for "..host);
198                         end
199                 end
200         end
201         
202         return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));       
203 end
204
205 function def_env.module:unload(name, hosts)
206         local mm = require "modulemanager";
207
208         hosts = get_hosts_set(hosts, name);
209         
210         -- Unload the module for each host
211         local ok, err, count = true, nil, 0;
212         for host in hosts do
213                 if mm.is_loaded(host, name) then
214                         ok, err = mm.unload(host, name);
215                         if not ok then
216                                 ok = false;
217                                 self.session.print(err or "Unknown error unloading module");
218                         else
219                                 count = count + 1;
220                                 self.session.print("Unloaded from "..host);
221                         end
222                 end
223         end
224         return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
225 end
226
227 function def_env.module:reload(name, hosts)
228         local mm = require "modulemanager";
229
230         hosts = get_hosts_set(hosts, name);
231         
232         -- Reload the module for each host
233         local ok, err, count = true, nil, 0;
234         for host in hosts do
235                 if mm.is_loaded(host, name) then
236                         ok, err = mm.reload(host, name);
237                         if not ok then
238                                 ok = false;
239                                 self.session.print(err or "Unknown error reloading module");
240                         else
241                                 count = count + 1;
242                                 if ok == nil then
243                                         ok = true;
244                                 end
245                                 self.session.print("Reloaded on "..host);
246                         end
247                 end
248         end
249         return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
250 end
251
252 def_env.config = {};
253 function def_env.config:load(filename, format)
254         local config_load = require "core.configmanager".load;
255         local ok, err = config_load(filename, format);
256         if not ok then
257                 return false, err or "Unknown error loading config";
258         end
259         return true, "Config loaded";
260 end
261
262 function def_env.config:get(host, section, key)
263         local config_get = require "core.configmanager".get
264         return true, tostring(config_get(host, section, key));
265 end
266
267 def_env.hosts = {};
268 function def_env.hosts:list()
269         for host, host_session in pairs(hosts) do
270                 self.session.print(host);
271         end
272         return true, "Done";
273 end
274
275 function def_env.hosts:add(name)
276 end
277
278 def_env.c2s = {};
279
280 local function show_c2s(callback)
281         for hostname, host in pairs(hosts) do
282                 for username, user in pairs(host.sessions or {}) do
283                         for resource, session in pairs(user.sessions or {}) do
284                                 local jid = username.."@"..hostname.."/"..resource;
285                                 callback(jid, session);
286                         end
287                 end
288         end
289 end
290
291 function def_env.c2s:show(match_jid)
292         local print, count = self.session.print, 0;
293         show_c2s(function (jid)
294                 if (not match_jid) or jid:match(match_jid) then
295                         count = count + 1;
296                         print(jid);
297                 end             
298         end);
299         return true, "Total: "..count.." clients";
300 end
301
302 function def_env.c2s:show_insecure(match_jid)
303         local print, count = self.session.print, 0;
304         show_c2s(function (jid, session)
305                 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
306                         count = count + 1;
307                         print(jid);
308                 end             
309         end);
310         return true, "Total: "..count.." insecure client connections";
311 end
312
313 function def_env.c2s:show_secure(match_jid)
314         local print, count = self.session.print, 0;
315         show_c2s(function (jid, session)
316                 if ((not match_jid) or jid:match(match_jid)) and session.secure then
317                         count = count + 1;
318                         print(jid);
319                 end             
320         end);
321         return true, "Total: "..count.." secure client connections";
322 end
323
324 function def_env.c2s:close(match_jid)
325         local print, count = self.session.print, 0;
326         show_c2s(function (jid, session)
327                 if jid == match_jid or jid_bare(jid) == match_jid then
328                         count = count + 1;
329                         session:close();
330                 end
331         end);
332         return true, "Total: "..count.." sessions closed";
333 end
334
335 def_env.s2s = {};
336 function def_env.s2s:show(match_jid)
337         local _print = self.session.print;
338         local print = self.session.print;
339         
340         local count_in, count_out = 0,0;
341         
342         for host, host_session in pairs(hosts) do
343                 print = function (...) _print(host); _print(...); print = _print; end
344                 for remotehost, session in pairs(host_session.s2sout) do
345                         if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
346                                 count_out = count_out + 1;
347                                 print("    "..host.." -> "..remotehost);
348                                 if session.sendq then
349                                         print("        There are "..#session.sendq.." queued outgoing stanzas for this connection");
350                                 end
351                                 if session.type == "s2sout_unauthed" then
352                                         if session.connecting then
353                                                 print("        Connection not yet established");
354                                                 if not session.srv_hosts then
355                                                         if not session.conn then
356                                                                 print("        We do not yet have a DNS answer for this host's SRV records");
357                                                         else
358                                                                 print("        This host has no SRV records, using A record instead");
359                                                         end
360                                                 elseif session.srv_choice then
361                                                         print("        We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
362                                                         local srv_choice = session.srv_hosts[session.srv_choice];
363                                                         print("        Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
364                                                 end
365                                         elseif session.notopen then
366                                                 print("        The <stream> has not yet been opened");
367                                         elseif not session.dialback_key then
368                                                 print("        Dialback has not been initiated yet");
369                                         elseif session.dialback_key then
370                                                 print("        Dialback has been requested, but no result received");
371                                         end
372                                 end
373                         end
374                 end     
375                 
376                 for session in pairs(incoming_s2s) do
377                         if session.to_host == host and ((not match_jid) or host:match(match_jid) 
378                                 or (session.from_host and session.from_host:match(match_jid))) then
379                                 count_in = count_in + 1;
380                                 print("    "..host.." <- "..(session.from_host or "(unknown)"));
381                                 if session.type == "s2sin_unauthed" then
382                                                 print("        Connection not yet authenticated");
383                                 end
384                                 for name in pairs(session.hosts) do
385                                         if name ~= session.from_host then
386                                                 print("        also hosts "..tostring(name));
387                                         end
388                                 end
389                         end
390                 end
391                 
392                 print = _print;
393         end
394         
395         for session in pairs(incoming_s2s) do
396                 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
397                         count_in = count_in + 1;
398                         print("Other incoming s2s connections");
399                         print("    (unknown) <- "..(session.from_host or "(unknown)"));                 
400                 end
401         end
402         
403         return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
404 end
405
406 function def_env.s2s:close(from, to)
407         local print, count = self.session.print, 0;
408         
409         if not (from and to) then
410                 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
411         elseif from == to then
412                 return false, "Both from and to are the same... you can't do that :)";
413         end
414         
415         if hosts[from] and not hosts[to] then
416                 -- Is an outgoing connection
417                 local session = hosts[from].s2sout[to];
418                 if not session then 
419                         print("No outgoing connection from "..from.." to "..to)
420                 else
421                         s2smanager.destroy_session(session);
422                         count = count + 1;
423                         print("Closed outgoing session from "..from.." to "..to);
424                 end
425         elseif hosts[to] and not hosts[from] then
426                 -- Is an incoming connection
427                 for session in pairs(incoming_s2s) do
428                         if session.to_host == to and session.from_host == from then
429                                 s2smanager.destroy_session(session);
430                                 count = count + 1;
431                         end
432                 end
433                 
434                 if count == 0 then
435                         print("No incoming connections from "..from.." to "..to);
436                 else
437                         print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
438                 end
439         elseif hosts[to] and hosts[from] then
440                 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
441         else
442                 return false, "Neither of the hostnames you specified are being used on this server";
443         end
444         
445         return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
446 end
447
448 -------------
449
450 function printbanner(session)
451         local option = config.get("*", "core", "console_banner");
452 if option == nil or option == "full" or option == "graphic" then
453 session.print [[
454                    ____                \   /     _       
455                     |  _ \ _ __ ___  ___  _-_   __| |_   _ 
456                     | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
457                     |  __/| | | (_) \__ \ |_| | (_| | |_| |
458                     |_|   |_|  \___/|___/\___/ \__,_|\__, |
459                     A study in simplicity            |___/ 
460
461 ]]
462 end
463 if option == nil or option == "short" or option == "full" then
464 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
465 session.print("You may find more help on using this console in our online documentation at ");
466 session.print("http://prosody.im/doc/console\n");
467 end
468 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
469         if type(option) == "string" then
470                 session.print(option)
471         elseif type(option) == "function" then
472                 setfenv(option, redirect_output(_G, session));
473                 pcall(option, session);
474         end
475 end
476 end