mod_tls: :up() out of the starttls tag in stream:features
[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         elseif section == "server" then
187                 print [[server:version() - Show the server's version number]]
188                 print [[server:uptime() - Show how long the server has been running]]
189                 --print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
190         elseif section == "console" then
191                 print [[Hey! Welcome to Prosody's admin console.]]
192                 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
193                 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
194                 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
195                 print [[]]
196                 print [[For now we offer a couple of handy shortcuts:]]
197                 print [[!! - Repeat the last command]]
198                 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
199                 print [[]]
200                 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
201                 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
202                 print [[the running server. Great fun, but be careful not to break anything :)]]
203         end
204         print [[]]
205 end
206
207 -- Session environment --
208 -- Anything in def_env will be accessible within the session as a global variable
209
210 def_env.server = {};
211
212 function def_env.server:insane_reload()
213         prosody.unlock_globals();
214         dofile "prosody"
215         prosody = _G.prosody;
216         return true, "Server reloaded";
217 end
218
219 function def_env.server:version()
220         return true, tostring(prosody.version or "unknown");
221 end
222
223 function def_env.server:uptime()
224         local t = os.time()-prosody.start_time;
225         local seconds = t%60;
226         t = (t - seconds)/60;
227         local minutes = t%60;
228         t = (t - minutes)/60;
229         local hours = t%24;
230         t = (t - hours)/24;
231         local days = t;
232         return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)", 
233                 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "", 
234                 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
235 end
236
237 function def_env.server:shutdown(reason)
238         prosody.shutdown(reason);
239         return true, "Shutdown initiated";
240 end
241
242 def_env.module = {};
243
244 local function get_hosts_set(hosts, module)
245         if type(hosts) == "table" then
246                 if hosts[1] then
247                         return set.new(hosts);
248                 elseif hosts._items then
249                         return hosts;
250                 end
251         elseif type(hosts) == "string" then
252                 return set.new { hosts };
253         elseif hosts == nil then
254                 local mm = require "modulemanager";
255                 return set.new(array.collect(keys(prosody.hosts)))
256                         / function (host) return prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module); end;
257         end
258 end
259
260 function def_env.module:load(name, hosts, config)
261         local mm = require "modulemanager";
262         
263         hosts = get_hosts_set(hosts);
264         
265         -- Load the module for each host
266         local ok, err, count = true, nil, 0;
267         for host in hosts do
268                 if (not mm.is_loaded(host, name)) then
269                         ok, err = mm.load(host, name, config);
270                         if not ok then
271                                 ok = false;
272                                 self.session.print(err or "Unknown error loading module");
273                         else
274                                 count = count + 1;
275                                 self.session.print("Loaded for "..host);
276                         end
277                 end
278         end
279         
280         return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));       
281 end
282
283 function def_env.module:unload(name, hosts)
284         local mm = require "modulemanager";
285
286         hosts = get_hosts_set(hosts, name);
287         
288         -- Unload the module for each host
289         local ok, err, count = true, nil, 0;
290         for host in hosts do
291                 if mm.is_loaded(host, name) then
292                         ok, err = mm.unload(host, name);
293                         if not ok then
294                                 ok = false;
295                                 self.session.print(err or "Unknown error unloading module");
296                         else
297                                 count = count + 1;
298                                 self.session.print("Unloaded from "..host);
299                         end
300                 end
301         end
302         return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
303 end
304
305 function def_env.module:reload(name, hosts)
306         local mm = require "modulemanager";
307
308         hosts = get_hosts_set(hosts, name);
309         
310         -- Reload the module for each host
311         local ok, err, count = true, nil, 0;
312         for host in hosts do
313                 if mm.is_loaded(host, name) then
314                         ok, err = mm.reload(host, name);
315                         if not ok then
316                                 ok = false;
317                                 self.session.print(err or "Unknown error reloading module");
318                         else
319                                 count = count + 1;
320                                 if ok == nil then
321                                         ok = true;
322                                 end
323                                 self.session.print("Reloaded on "..host);
324                         end
325                 end
326         end
327         return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
328 end
329
330 def_env.config = {};
331 function def_env.config:load(filename, format)
332         local config_load = require "core.configmanager".load;
333         local ok, err = config_load(filename, format);
334         if not ok then
335                 return false, err or "Unknown error loading config";
336         end
337         return true, "Config loaded";
338 end
339
340 function def_env.config:get(host, section, key)
341         local config_get = require "core.configmanager".get
342         return true, tostring(config_get(host, section, key));
343 end
344
345 function def_env.config:reload()
346         local ok, err = prosody.reload_config();
347         return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
348 end
349
350 def_env.hosts = {};
351 function def_env.hosts:list()
352         for host, host_session in pairs(hosts) do
353                 self.session.print(host);
354         end
355         return true, "Done";
356 end
357
358 function def_env.hosts:add(name)
359 end
360
361 def_env.c2s = {};
362
363 local function show_c2s(callback)
364         for hostname, host in pairs(hosts) do
365                 for username, user in pairs(host.sessions or {}) do
366                         for resource, session in pairs(user.sessions or {}) do
367                                 local jid = username.."@"..hostname.."/"..resource;
368                                 callback(jid, session);
369                         end
370                 end
371         end
372 end
373
374 function def_env.c2s:show(match_jid)
375         local print, count = self.session.print, 0;
376         local curr_host;
377         show_c2s(function (jid, session)
378                 if curr_host ~= session.host then
379                         curr_host = session.host;
380                         print(curr_host);
381                 end
382                 if (not match_jid) or jid:match(match_jid) then
383                         count = count + 1;
384                         local status, priority = "unavailable", tostring(session.priority or "-");
385                         if session.presence then
386                                 status = session.presence:child_with_name("show");
387                                 if status then
388                                         status = status:get_text() or "[invalid!]";
389                                 else
390                                         status = "available";
391                                 end
392                         end
393                         print("   "..jid.." - "..status.."("..priority..")");
394                 end             
395         end);
396         return true, "Total: "..count.." clients";
397 end
398
399 function def_env.c2s:show_insecure(match_jid)
400         local print, count = self.session.print, 0;
401         show_c2s(function (jid, session)
402                 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
403                         count = count + 1;
404                         print(jid);
405                 end             
406         end);
407         return true, "Total: "..count.." insecure client connections";
408 end
409
410 function def_env.c2s:show_secure(match_jid)
411         local print, count = self.session.print, 0;
412         show_c2s(function (jid, session)
413                 if ((not match_jid) or jid:match(match_jid)) and session.secure then
414                         count = count + 1;
415                         print(jid);
416                 end             
417         end);
418         return true, "Total: "..count.." secure client connections";
419 end
420
421 function def_env.c2s:close(match_jid)
422         local print, count = self.session.print, 0;
423         show_c2s(function (jid, session)
424                 if jid == match_jid or jid_bare(jid) == match_jid then
425                         count = count + 1;
426                         session:close();
427                 end
428         end);
429         return true, "Total: "..count.." sessions closed";
430 end
431
432 def_env.s2s = {};
433 function def_env.s2s:show(match_jid)
434         local _print = self.session.print;
435         local print = self.session.print;
436         
437         local count_in, count_out = 0,0;
438         
439         for host, host_session in pairs(hosts) do
440                 print = function (...) _print(host); _print(...); print = _print; end
441                 for remotehost, session in pairs(host_session.s2sout) do
442                         if (not match_jid) or remotehost:match(match_jid) or host:match(match_jid) then
443                                 count_out = count_out + 1;
444                                 print("    "..host.." -> "..remotehost);
445                                 if session.sendq then
446                                         print("        There are "..#session.sendq.." queued outgoing stanzas for this connection");
447                                 end
448                                 if session.type == "s2sout_unauthed" then
449                                         if session.connecting then
450                                                 print("        Connection not yet established");
451                                                 if not session.srv_hosts then
452                                                         if not session.conn then
453                                                                 print("        We do not yet have a DNS answer for this host's SRV records");
454                                                         else
455                                                                 print("        This host has no SRV records, using A record instead");
456                                                         end
457                                                 elseif session.srv_choice then
458                                                         print("        We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
459                                                         local srv_choice = session.srv_hosts[session.srv_choice];
460                                                         print("        Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
461                                                 end
462                                         elseif session.notopen then
463                                                 print("        The <stream> has not yet been opened");
464                                         elseif not session.dialback_key then
465                                                 print("        Dialback has not been initiated yet");
466                                         elseif session.dialback_key then
467                                                 print("        Dialback has been requested, but no result received");
468                                         end
469                                 end
470                         end
471                 end     
472                 
473                 for session in pairs(incoming_s2s) do
474                         if session.to_host == host and ((not match_jid) or host:match(match_jid) 
475                                 or (session.from_host and session.from_host:match(match_jid))) then
476                                 count_in = count_in + 1;
477                                 print("    "..host.." <- "..(session.from_host or "(unknown)"));
478                                 if session.type == "s2sin_unauthed" then
479                                                 print("        Connection not yet authenticated");
480                                 end
481                                 for name in pairs(session.hosts) do
482                                         if name ~= session.from_host then
483                                                 print("        also hosts "..tostring(name));
484                                         end
485                                 end
486                         end
487                 end
488                 
489                 print = _print;
490         end
491         
492         for session in pairs(incoming_s2s) do
493                 if not session.to_host and ((not match_jid) or session.from_host and session.from_host:match(match_jid)) then
494                         count_in = count_in + 1;
495                         print("Other incoming s2s connections");
496                         print("    (unknown) <- "..(session.from_host or "(unknown)"));                 
497                 end
498         end
499         
500         return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
501 end
502
503 function def_env.s2s:close(from, to)
504         local print, count = self.session.print, 0;
505         
506         if not (from and to) then
507                 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
508         elseif from == to then
509                 return false, "Both from and to are the same... you can't do that :)";
510         end
511         
512         if hosts[from] and not hosts[to] then
513                 -- Is an outgoing connection
514                 local session = hosts[from].s2sout[to];
515                 if not session then 
516                         print("No outgoing connection from "..from.." to "..to)
517                 else
518                         (session.close or s2smanager.destroy_session)(session);
519                         count = count + 1;
520                         print("Closed outgoing session from "..from.." to "..to);
521                 end
522         elseif hosts[to] and not hosts[from] then
523                 -- Is an incoming connection
524                 for session in pairs(incoming_s2s) do
525                         if session.to_host == to and session.from_host == from then
526                                 (session.close or s2smanager.destroy_session)(session);
527                                 count = count + 1;
528                         end
529                 end
530                 
531                 if count == 0 then
532                         print("No incoming connections from "..from.." to "..to);
533                 else
534                         print("Closed "..count.." incoming session"..((count == 1 and "") or "s").." from "..from.." to "..to);
535                 end
536         elseif hosts[to] and hosts[from] then
537                 return false, "Both of the hostnames you specified are local, there are no s2s sessions to close";
538         else
539                 return false, "Neither of the hostnames you specified are being used on this server";
540         end
541         
542         return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
543 end
544
545 -------------
546
547 function printbanner(session)
548         local option = config.get("*", "core", "console_banner");
549 if option == nil or option == "full" or option == "graphic" then
550 session.print [[
551                    ____                \   /     _       
552                     |  _ \ _ __ ___  ___  _-_   __| |_   _ 
553                     | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
554                     |  __/| | | (_) \__ \ |_| | (_| | |_| |
555                     |_|   |_|  \___/|___/\___/ \__,_|\__, |
556                     A study in simplicity            |___/ 
557
558 ]]
559 end
560 if option == nil or option == "short" or option == "full" then
561 session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
562 session.print("You may find more help on using this console in our online documentation at ");
563 session.print("http://prosody.im/doc/console\n");
564 end
565 if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
566         if type(option) == "string" then
567                 session.print(option)
568         elseif type(option) == "function" then
569                 setfenv(option, redirect_output(_G, session));
570                 pcall(option, session);
571         end
572 end
573 end