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