mod_ping: Convert from Windows line endings
[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 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 -- Session environment --
160 -- Anything in def_env will be accessible within the session as a global variable
161
162 def_env.server = {};
163 function def_env.server:reload()
164         prosody.unlock_globals();
165         dofile "prosody"
166         prosody = _G.prosody;
167         return true, "Server reloaded";
168 end
169
170 function def_env.server:version()
171         return true, tostring(prosody.version or "unknown");
172 end
173
174 function def_env.server:uptime()
175         local t = os.time()-prosody.start_time;
176         local seconds = t%60;
177         t = (t - seconds)/60;
178         local minutes = t%60;
179         t = (t - minutes)/60;
180         local hours = t%24;
181         t = (t - hours)/24;
182         local days = t;
183         return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)", 
184                 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "", 
185                 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
186 end
187
188 def_env.module = {};
189
190 local function get_hosts_set(hosts, module)
191         if type(hosts) == "table" then
192                 if hosts[1] then
193                         return set.new(hosts);
194                 elseif hosts._items then
195                         return hosts;
196                 end
197         elseif type(hosts) == "string" then
198                 return set.new { hosts };
199         elseif hosts == nil then
200                 local mm = require "modulemanager";
201                 return set.new(array.collect(keys(prosody.hosts)))
202                         / function (host) return prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module); end;
203         end
204 end
205
206 function def_env.module:load(name, hosts, config)
207         local mm = require "modulemanager";
208         
209         hosts = get_hosts_set(hosts);
210         
211         -- Load the module for each host
212         local ok, err, count = true, nil, 0;
213         for host in hosts do
214                 if (not mm.is_loaded(host, name)) then
215                         ok, err = mm.load(host, name, config);
216                         if not ok then
217                                 ok = false;
218                                 self.session.print(err or "Unknown error loading module");
219                         else
220                                 count = count + 1;
221                                 self.session.print("Loaded for "..host);
222                         end
223                 end
224         end
225         
226         return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));       
227 end
228
229 function def_env.module:unload(name, hosts)
230         local mm = require "modulemanager";
231
232         hosts = get_hosts_set(hosts, name);
233         
234         -- Unload the module for each host
235         local ok, err, count = true, nil, 0;
236         for host in hosts do
237                 if mm.is_loaded(host, name) then
238                         ok, err = mm.unload(host, name);
239                         if not ok then
240                                 ok = false;
241                                 self.session.print(err or "Unknown error unloading module");
242                         else
243                                 count = count + 1;
244                                 self.session.print("Unloaded from "..host);
245                         end
246                 end
247         end
248         return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
249 end
250
251 function def_env.module:reload(name, hosts)
252         local mm = require "modulemanager";
253
254         hosts = get_hosts_set(hosts, name);
255         
256         -- Reload the module for each host
257         local ok, err, count = true, nil, 0;
258         for host in hosts do
259                 if mm.is_loaded(host, name) then
260                         ok, err = mm.reload(host, name);
261                         if not ok then
262                                 ok = false;
263                                 self.session.print(err or "Unknown error reloading module");
264                         else
265                                 count = count + 1;
266                                 if ok == nil then
267                                         ok = true;
268                                 end
269                                 self.session.print("Reloaded on "..host);
270                         end
271                 end
272         end
273         return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
274 end
275
276 def_env.config = {};
277 function def_env.config:load(filename, format)
278         local config_load = require "core.configmanager".load;
279         local ok, err = config_load(filename, format);
280         if not ok then
281                 return false, err or "Unknown error loading config";
282         end
283         return true, "Config loaded";
284 end
285
286 function def_env.config:get(host, section, key)
287         local config_get = require "core.configmanager".get
288         return true, tostring(config_get(host, section, key));
289 end
290
291 def_env.hosts = {};
292 function def_env.hosts:list()
293         for host, host_session in pairs(hosts) do
294                 self.session.print(host);
295         end
296         return true, "Done";
297 end
298
299 function def_env.hosts:add(name)
300 end
301
302 def_env.c2s = {};
303
304 local function show_c2s(callback)
305         for hostname, host in pairs(hosts) do
306                 for username, user in pairs(host.sessions or {}) do
307                         for resource, session in pairs(user.sessions or {}) do
308                                 local jid = username.."@"..hostname.."/"..resource;
309                                 callback(jid, session);
310                         end
311                 end
312         end
313 end
314
315 function def_env.c2s:show(match_jid)
316         local print, count = self.session.print, 0;
317         show_c2s(function (jid)
318                 if (not match_jid) or jid:match(match_jid) then
319                         count = count + 1;
320                         print(jid);
321                 end             
322         end);
323         return true, "Total: "..count.." clients";
324 end
325
326 function def_env.c2s:show_insecure(match_jid)
327         local print, count = self.session.print, 0;
328         show_c2s(function (jid, session)
329                 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
330                         count = count + 1;
331                         print(jid);
332                 end             
333         end);
334         return true, "Total: "..count.." insecure client connections";
335 end
336
337 function def_env.c2s:show_secure(match_jid)
338         local print, count = self.session.print, 0;
339         show_c2s(function (jid, session)
340                 if ((not match_jid) or jid:match(match_jid)) and session.secure then
341                         count = count + 1;
342                         print(jid);
343                 end             
344         end);
345         return true, "Total: "..count.." secure client connections";
346 end
347
348 function def_env.c2s:close(match_jid)
349         local print, count = self.session.print, 0;
350         show_c2s(function (jid, session)
351                 if jid == match_jid or jid_bare(jid) == match_jid then
352                         count = count + 1;
353                         session:close();
354                 end
355         end);
356         return true, "Total: "..count.." sessions closed";
357 end
358
359 def_env.s2s = {};
360 function def_env.s2s:show(match_jid)
361         local _print = self.session.print;
362         local print = self.session.print;
363         
364         local count_in, count_out = 0,0;
365         
366         for host, host_session in pairs(hosts) do
367                 print = function (...) _print(host); _print(...); print = _print; end
368                 for remotehost, session in pairs(host_session.s2sout) do
369                         if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
370                                 count_out = count_out + 1;
371                                 print("    "..host.." -> "..remotehost);
372                                 if session.sendq then
373                                         print("        There are "..#session.sendq.." queued outgoing stanzas for this connection");
374                                 end
375                                 if session.type == "s2sout_unauthed" then
376                                         if session.connecting then
377                                                 print("        Connection not yet established");
378                                                 if not session.srv_hosts then
379                                                         if not session.conn then
380                                                                 print("        We do not yet have a DNS answer for this host's SRV records");
381                                                         else
382                                                                 print("        This host has no SRV records, using A record instead");
383                                                         end
384                                                 elseif session.srv_choice then
385                                                         print("        We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
386                                                         local srv_choice = session.srv_hosts[session.srv_choice];
387                                                         print("        Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
388                                                 end
389                                         elseif session.notopen then
390                                                 print("        The <stream> has not yet been opened");
391                                         elseif not session.dialback_key then
392                                                 print("        Dialback has not been initiated yet");
393                                         elseif session.dialback_key then
394                                                 print("        Dialback has been requested, but no result received");
395                                         end
396                                 end
397                         end
398                 end     
399                 
400                 for session in pairs(incoming_s2s) do
401                         if session.to_host == host and ((not match_jid) or host:match(match_jid) 
402                                 or (session.from_host and session.from_host:match(match_jid))) then
403                                 count_in = count_in + 1;
404                                 print("    "..host.." <- "..(session.from_host or "(unknown)"));
405                                 if session.type == "s2sin_unauthed" then
406                                                 print("        Connection not yet authenticated");
407                                 end
408                                 for name in pairs(session.hosts) do
409                                         if name ~= session.from_host then
410                                                 print("        also hosts "..tostring(name));
411                                         end
412                                 end
413                         end
414                 end
415                 
416                 print = _print;
417         end
418         
419         for session in pairs(incoming_s2s) do
420                 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
421                         count_in = count_in + 1;
422                         print("Other incoming s2s connections");
423                         print("    (unknown) <- "..(session.from_host or "(unknown)"));                 
424                 end
425         end
426         
427         return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
428 end
429
430 function def_env.s2s:close(from, to)
431         local print, count = self.session.print, 0;
432         
433         if not (from and to) then
434                 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
435         elseif from == to then
436                 return false, "Both from and to are the same... you can't do that :)";
437         end
438         
439         if hosts[from] and not hosts[to] then
440                 -- Is an outgoing connection
441                 local session = hosts[from].s2sout[to];
442                 if not session then 
443                         print("No outgoing connection from "..from.." to "..to)
444                 else
445                         s2smanager.destroy_session(session);
446                         count = count + 1;
447                         print("Closed outgoing session from "..from.." to "..to);
448                 end
449         elseif hosts[to] and not hosts[from] then
450                 -- Is an incoming connection
451                 for session in pairs(incoming_s2s) do
452                         if session.to_host == to and session.from_host == from then
453                                 s2smanager.destroy_session(session);
454                                 count = count + 1;
455                         end
456                 end
457                 
458                 if count == 0 then
459                         print("No incoming connections from "..from.." to "..to);
460                 else
461                         print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
462                 end
463         elseif hosts[to] and hosts[from] then
464                 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
465         else
466                 return false, "Neither of the hostnames you specified are being used on this server";
467         end
468         
469         return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
470 end
471
472 -------------
473
474 function printbanner(session)
475         local option = config.get("*", "core", "console_banner");
476 if option == nil or option == "full" or option == "graphic" then
477 session.print [[
478                    ____                \   /     _       
479                     |  _ \ _ __ ___  ___  _-_   __| |_   _ 
480                     | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
481                     |  __/| | | (_) \__ \ |_| | (_| | |_| |
482                     |_|   |_|  \___/|___/\___/ \__,_|\__, |
483                     A study in simplicity            |___/ 
484
485 ]]
486 end
487 if option == nil or option == "short" or option == "full" then
488 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
489 session.print("You may find more help on using this console in our online documentation at ");
490 session.print("http://prosody.im/doc/console\n");
491 end
492 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
493         if type(option) == "string" then
494                 session.print(option)
495         elseif type(option) == "function" then
496                 setfenv(option, redirect_output(_G, session));
497                 pcall(option, session);
498         end
499 end
500 end