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