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