Merge 0.9->0.10
[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:set_global();
10
11 local hostmanager = require "core.hostmanager";
12 local modulemanager = require "core.modulemanager";
13 local s2smanager = require "core.s2smanager";
14 local portmanager = require "core.portmanager";
15
16 local _G = _G;
17
18 local prosody = _G.prosody;
19 local hosts = prosody.hosts;
20
21 local console_listener = { default_port = 5582; default_mode = "*a"; interface = "127.0.0.1" };
22
23 local iterators = require "util.iterators";
24 local keys, values = iterators.keys, iterators.values;
25 local jid_bare, jid_split = import("util.jid", "bare", "prepped_split");
26 local set, array = require "util.set", require "util.array";
27 local cert_verify_identity = require "util.x509".verify_identity;
28 local envload = require "util.envload".envload;
29 local envloadfile = require "util.envload".envloadfile;
30
31 local commands = module:shared("commands")
32 local def_env = module:shared("env");
33 local default_env_mt = { __index = def_env };
34 local core_post_stanza = prosody.core_post_stanza;
35
36 local function redirect_output(_G, session)
37         local env = setmetatable({ print = session.print }, { __index = function (t, k) return rawget(_G, k); end });
38         env.dofile = function(name)
39                 local f, err = envloadfile(name, env);
40                 if not f then return f, err; end
41                 return f();
42         end;
43         return env;
44 end
45
46 console = {};
47
48 function console:new_session(conn)
49         local w = function(s) conn:write(s:gsub("\n", "\r\n")); end;
50         local session = { conn = conn;
51                         send = function (t) w(tostring(t)); end;
52                         print = function (...)
53                                 local t = {};
54                                 for i=1,select("#", ...) do
55                                         t[i] = tostring(select(i, ...));
56                                 end
57                                 w("| "..table.concat(t, "\t").."\n");
58                         end;
59                         disconnect = function () conn:close(); end;
60                         };
61         session.env = setmetatable({}, default_env_mt);
62
63         -- Load up environment with helper objects
64         for name, t in pairs(def_env) do
65                 if type(t) == "table" then
66                         session.env[name] = setmetatable({ session = session }, { __index = t });
67                 end
68         end
69
70         return session;
71 end
72
73 function console:process_line(session, line)
74         local useglobalenv;
75
76         if line:match("^>") then
77                 line = line:gsub("^>", "");
78                 useglobalenv = true;
79         elseif line == "\004" then
80                 commands["bye"](session, line);
81                 return;
82         else
83                 local command = line:match("^%w+") or line:match("%p");
84                 if commands[command] then
85                         commands[command](session, line);
86                         return;
87                 end
88         end
89
90         session.env._ = line;
91
92         local chunkname = "=console";
93         local env = (useglobalenv and redirect_output(_G, session)) or session.env or nil
94         local chunk, err = envload("return "..line, chunkname, env);
95         if not chunk then
96                 chunk, err = envload(line, chunkname, env);
97                 if not chunk then
98                         err = err:gsub("^%[string .-%]:%d+: ", "");
99                         err = err:gsub("^:%d+: ", "");
100                         err = err:gsub("'<eof>'", "the end of the line");
101                         session.print("Sorry, I couldn't understand that... "..err);
102                         return;
103                 end
104         end
105
106         local ranok, taskok, message = pcall(chunk);
107
108         if not (ranok or message or useglobalenv) and commands[line:lower()] then
109                 commands[line:lower()](session, line);
110                 return;
111         end
112
113         if not ranok then
114                 session.print("Fatal error while running command, it did not complete");
115                 session.print("Error: "..taskok);
116                 return;
117         end
118
119         if not message then
120                 session.print("Result: "..tostring(taskok));
121                 return;
122         elseif (not taskok) and message then
123                 session.print("Command completed with a problem");
124                 session.print("Message: "..tostring(message));
125                 return;
126         end
127
128         session.print("OK: "..tostring(message));
129 end
130
131 local sessions = {};
132
133 function console_listener.onconnect(conn)
134         -- Handle new connection
135         local session = console:new_session(conn);
136         sessions[conn] = session;
137         printbanner(session);
138         session.send(string.char(0));
139 end
140
141 function console_listener.onincoming(conn, data)
142         local session = sessions[conn];
143
144         local partial = session.partial_data;
145         if partial then
146                 data = partial..data;
147         end
148
149         for line in data:gmatch("[^\n]*[\n\004]") do
150                 if session.closed then return end
151                 console:process_line(session, line);
152                 session.send(string.char(0));
153         end
154         session.partial_data = data:match("[^\n]+$");
155 end
156
157 function console_listener.onreadtimeout(conn)
158         local session = sessions[conn];
159         if session then
160                 session.send("\0");
161                 return true;
162         end
163 end
164
165 function console_listener.ondisconnect(conn, err)
166         local session = sessions[conn];
167         if session then
168                 session.disconnect();
169                 sessions[conn] = nil;
170         end
171 end
172
173 function console_listener.ondetach(conn)
174         sessions[conn] = nil;
175 end
176
177 -- Console commands --
178 -- These are simple commands, not valid standalone in Lua
179
180 function commands.bye(session)
181         session.print("See you! :)");
182         session.closed = true;
183         session.disconnect();
184 end
185 commands.quit, commands.exit = commands.bye, commands.bye;
186
187 commands["!"] = function (session, data)
188         if data:match("^!!") and session.env._ then
189                 session.print("!> "..session.env._);
190                 return console_listener.onincoming(session.conn, session.env._);
191         end
192         local old, new = data:match("^!(.-[^\\])!(.-)!$");
193         if old and new then
194                 local ok, res = pcall(string.gsub, session.env._, old, new);
195                 if not ok then
196                         session.print(res)
197                         return;
198                 end
199                 session.print("!> "..res);
200                 return console_listener.onincoming(session.conn, res);
201         end
202         session.print("Sorry, not sure what you want");
203 end
204
205
206 function commands.help(session, data)
207         local print = session.print;
208         local section = data:match("^help (%w+)");
209         if not section then
210                 print [[Commands are divided into multiple sections. For help on a particular section, ]]
211                 print [[type: help SECTION (for example, 'help c2s'). Sections are: ]]
212                 print [[]]
213                 print [[c2s - Commands to manage local client-to-server sessions]]
214                 print [[s2s - Commands to manage sessions between this server and others]]
215                 print [[module - Commands to load/reload/unload modules/plugins]]
216                 print [[host - Commands to activate, deactivate and list virtual hosts]]
217                 print [[user - Commands to create and delete users, and change their passwords]]
218                 print [[server - Uptime, version, shutting down, etc.]]
219                 print [[port - Commands to manage ports the server is listening on]]
220                 print [[dns - Commands to manage and inspect the internal DNS resolver]]
221                 print [[config - Reloading the configuration, etc.]]
222                 print [[console - Help regarding the console itself]]
223         elseif section == "c2s" then
224                 print [[c2s:show(jid) - Show all client sessions with the specified JID (or all if no JID given)]]
225                 print [[c2s:show_insecure() - Show all unencrypted client connections]]
226                 print [[c2s:show_secure() - Show all encrypted client connections]]
227                 print [[c2s:show_tls() - Show TLS cipher info for encrypted sessions]]
228                 print [[c2s:close(jid) - Close all sessions for the specified JID]]
229         elseif section == "s2s" then
230                 print [[s2s:show(domain) - Show all s2s connections for the given domain (or all if no domain given)]]
231                 print [[s2s:show_tls(domain) - Show TLS cipher info for encrypted sessions]]
232                 print [[s2s:close(from, to) - Close a connection from one domain to another]]
233                 print [[s2s:closeall(host) - Close all the incoming/outgoing s2s sessions to specified host]]
234         elseif section == "module" then
235                 print [[module:load(module, host) - Load the specified module on the specified host (or all hosts if none given)]]
236                 print [[module:reload(module, host) - The same, but unloads and loads the module (saving state if the module supports it)]]
237                 print [[module:unload(module, host) - The same, but just unloads the module from memory]]
238                 print [[module:list(host) - List the modules loaded on the specified host]]
239         elseif section == "host" then
240                 print [[host:activate(hostname) - Activates the specified host]]
241                 print [[host:deactivate(hostname) - Disconnects all clients on this host and deactivates]]
242                 print [[host:list() - List the currently-activated hosts]]
243         elseif section == "user" then
244                 print [[user:create(jid, password) - Create the specified user account]]
245                 print [[user:password(jid, password) - Set the password for the specified user account]]
246                 print [[user:delete(jid) - Permanently remove the specified user account]]
247                 print [[user:list(hostname, pattern) - List users on the specified host, optionally filtering with a pattern]]
248         elseif section == "server" then
249                 print [[server:version() - Show the server's version number]]
250                 print [[server:uptime() - Show how long the server has been running]]
251                 print [[server:memory() - Show details about the server's memory usage]]
252                 print [[server:shutdown(reason) - Shut down the server, with an optional reason to be broadcast to all connections]]
253         elseif section == "port" then
254                 print [[port:list() - Lists all network ports prosody currently listens on]]
255                 print [[port:close(port, interface) - Close a port]]
256         elseif section == "dns" then
257                 print [[dns:lookup(name, type, class) - Do a DNS lookup]]
258                 print [[dns:addnameserver(nameserver) - Add a nameserver to the list]]
259                 print [[dns:setnameserver(nameserver) - Replace the list of name servers with the supplied one]]
260                 print [[dns:purge() - Clear the DNS cache]]
261                 print [[dns:cache() - Show cached records]]
262         elseif section == "config" then
263                 print [[config:reload() - Reload the server configuration. Modules may need to be reloaded for changes to take effect.]]
264         elseif section == "console" then
265                 print [[Hey! Welcome to Prosody's admin console.]]
266                 print [[First thing, if you're ever wondering how to get out, simply type 'quit'.]]
267                 print [[Secondly, note that we don't support the full telnet protocol yet (it's coming)]]
268                 print [[so you may have trouble using the arrow keys, etc. depending on your system.]]
269                 print [[]]
270                 print [[For now we offer a couple of handy shortcuts:]]
271                 print [[!! - Repeat the last command]]
272                 print [[!old!new! - repeat the last command, but with 'old' replaced by 'new']]
273                 print [[]]
274                 print [[For those well-versed in Prosody's internals, or taking instruction from those who are,]]
275                 print [[you can prefix a command with > to escape the console sandbox, and access everything in]]
276                 print [[the running server. Great fun, but be careful not to break anything :)]]
277         end
278         print [[]]
279 end
280
281 -- Session environment --
282 -- Anything in def_env will be accessible within the session as a global variable
283
284 def_env.server = {};
285
286 function def_env.server:insane_reload()
287         prosody.unlock_globals();
288         dofile "prosody"
289         prosody = _G.prosody;
290         return true, "Server reloaded";
291 end
292
293 function def_env.server:version()
294         return true, tostring(prosody.version or "unknown");
295 end
296
297 function def_env.server:uptime()
298         local t = os.time()-prosody.start_time;
299         local seconds = t%60;
300         t = (t - seconds)/60;
301         local minutes = t%60;
302         t = (t - minutes)/60;
303         local hours = t%24;
304         t = (t - hours)/24;
305         local days = t;
306         return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
307                 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
308                 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
309 end
310
311 function def_env.server:shutdown(reason)
312         prosody.shutdown(reason);
313         return true, "Shutdown initiated";
314 end
315
316 local function human(kb)
317         local unit = "K";
318         if kb > 1024 then
319                 kb, unit = kb/1024, "M";
320         end
321         return ("%0.2f%sB"):format(kb, unit);
322 end
323
324 function def_env.server:memory()
325         if not pposix.meminfo then
326                 return true, "Lua is using "..collectgarbage("count");
327         end
328         local mem, lua_mem = pposix.meminfo(), collectgarbage("count");
329         local print = self.session.print;
330         print("Process: "..human((mem.allocated+mem.allocated_mmap)/1024));
331         print("   Used: "..human(mem.used/1024).." ("..human(lua_mem).." by Lua)");
332         print("   Free: "..human(mem.unused/1024).." ("..human(mem.returnable/1024).." returnable)");
333         return true, "OK";
334 end
335
336 def_env.module = {};
337
338 local function get_hosts_set(hosts, module)
339         if type(hosts) == "table" then
340                 if hosts[1] then
341                         return set.new(hosts);
342                 elseif hosts._items then
343                         return hosts;
344                 end
345         elseif type(hosts) == "string" then
346                 return set.new { hosts };
347         elseif hosts == nil then
348                 local mm = require "modulemanager";
349                 local hosts_set = set.new(array.collect(keys(prosody.hosts)))
350                         / function (host) return (prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module)) and host or nil; end;
351                 if module and mm.get_module("*", module) then
352                         hosts_set:add("*");
353                 end
354                 return hosts_set;
355         end
356 end
357
358 function def_env.module:load(name, hosts, config)
359         local mm = require "modulemanager";
360
361         hosts = get_hosts_set(hosts);
362
363         -- Load the module for each host
364         local ok, err, count, mod = true, nil, 0, nil;
365         for host in hosts do
366                 if (not mm.is_loaded(host, name)) then
367                         mod, err = mm.load(host, name, config);
368                         if not mod then
369                                 ok = false;
370                                 if err == "global-module-already-loaded" then
371                                         if count > 0 then
372                                                 ok, err, count = true, nil, 1;
373                                         end
374                                         break;
375                                 end
376                                 self.session.print(err or "Unknown error loading module");
377                         else
378                                 count = count + 1;
379                                 self.session.print("Loaded for "..mod.module.host);
380                         end
381                 end
382         end
383
384         return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
385 end
386
387 function def_env.module:unload(name, hosts)
388         local mm = require "modulemanager";
389
390         hosts = get_hosts_set(hosts, name);
391
392         -- Unload the module for each host
393         local ok, err, count = true, nil, 0;
394         for host in hosts do
395                 if mm.is_loaded(host, name) then
396                         ok, err = mm.unload(host, name);
397                         if not ok then
398                                 ok = false;
399                                 self.session.print(err or "Unknown error unloading module");
400                         else
401                                 count = count + 1;
402                                 self.session.print("Unloaded from "..host);
403                         end
404                 end
405         end
406         return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
407 end
408
409 function def_env.module:reload(name, hosts)
410         local mm = require "modulemanager";
411
412         hosts = array.collect(get_hosts_set(hosts, name)):sort(function (a, b)
413                 if a == "*" then return true
414                 elseif b == "*" then return false
415                 else return a < b; end
416         end);
417
418         -- Reload the module for each host
419         local ok, err, count = true, nil, 0;
420         for _, host in ipairs(hosts) do
421                 if mm.is_loaded(host, name) then
422                         ok, err = mm.reload(host, name);
423                         if not ok then
424                                 ok = false;
425                                 self.session.print(err or "Unknown error reloading module");
426                         else
427                                 count = count + 1;
428                                 if ok == nil then
429                                         ok = true;
430                                 end
431                                 self.session.print("Reloaded on "..host);
432                         end
433                 end
434         end
435         return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
436 end
437
438 function def_env.module:list(hosts)
439         if hosts == nil then
440                 hosts = array.collect(keys(prosody.hosts));
441                 table.insert(hosts, 1, "*");
442         end
443         if type(hosts) == "string" then
444                 hosts = { hosts };
445         end
446         if type(hosts) ~= "table" then
447                 return false, "Please supply a host or a list of hosts you would like to see";
448         end
449
450         local print = self.session.print;
451         for _, host in ipairs(hosts) do
452                 print((host == "*" and "Global" or host)..":");
453                 local modules = array.collect(keys(modulemanager.get_modules(host) or {})):sort();
454                 if #modules == 0 then
455                         if prosody.hosts[host] then
456                                 print("    No modules loaded");
457                         else
458                                 print("    Host not found");
459                         end
460                 else
461                         for _, name in ipairs(modules) do
462                                 print("    "..name);
463                         end
464                 end
465         end
466 end
467
468 def_env.config = {};
469 function def_env.config:load(filename, format)
470         local config_load = require "core.configmanager".load;
471         local ok, err = config_load(filename, format);
472         if not ok then
473                 return false, err or "Unknown error loading config";
474         end
475         return true, "Config loaded";
476 end
477
478 function def_env.config:get(host, section, key)
479         local config_get = require "core.configmanager".get
480         return true, tostring(config_get(host, section, key));
481 end
482
483 function def_env.config:reload()
484         local ok, err = prosody.reload_config();
485         return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
486 end
487
488 local function common_info(session, line)
489         if session.id then
490                 line[#line+1] = "["..session.id.."]"
491         else
492                 line[#line+1] = "["..session.type..(tostring(session):match("%x*$")).."]"
493         end
494 end
495
496 local function session_flags(session, line)
497         line = line or {};
498         common_info(session, line);
499         if session.type == "c2s" then
500                 local status, priority = "unavailable", tostring(session.priority or "-");
501                 if session.presence then
502                         status = session.presence:get_child_text("show") or "available";
503                 end
504                 line[#line+1] = status.."("..priority..")";
505         end
506         if session.cert_identity_status == "valid" then
507                 line[#line+1] = "(authenticated)";
508         end
509         if session.secure then
510                 line[#line+1] = "(encrypted)";
511         end
512         if session.compressed then
513                 line[#line+1] = "(compressed)";
514         end
515         if session.smacks then
516                 line[#line+1] = "(sm)";
517         end
518         if session.ip and session.ip:match(":") then
519                 line[#line+1] = "(IPv6)";
520         end
521         return table.concat(line, " ");
522 end
523
524 local function tls_info(session, line)
525         line = line or {};
526         common_info(session, line);
527         if session.secure then
528                 local sock = session.conn and session.conn.socket and session.conn:socket();
529                 if sock and sock.info then
530                         local info = sock:info();
531                         line[#line+1] = ("(%s with %s)"):format(info.protocol, info.cipher);
532                 else
533                         line[#line+1] = "(cipher info unavailable)";
534                 end
535         else
536                 line[#line+1] = "(insecure)";
537         end
538         return table.concat(line, " ");
539 end
540
541 def_env.c2s = {};
542
543 local function show_c2s(callback)
544         for hostname, host in pairs(hosts) do
545                 for username, user in pairs(host.sessions or {}) do
546                         for resource, session in pairs(user.sessions or {}) do
547                                 local jid = username.."@"..hostname.."/"..resource;
548                                 callback(jid, session);
549                         end
550                 end
551         end
552 end
553
554 function def_env.c2s:count(match_jid)
555         local count = 0;
556         show_c2s(function (jid, session)
557                 if (not match_jid) or jid:match(match_jid) then
558                         count = count + 1;
559                 end
560         end);
561         return true, "Total: "..count.." clients";
562 end
563
564 function def_env.c2s:show(match_jid, annotate)
565         local print, count = self.session.print, 0;
566         annotate = annotate or session_flags;
567         local curr_host;
568         show_c2s(function (jid, session)
569                 if curr_host ~= session.host then
570                         curr_host = session.host;
571                         print(curr_host);
572                 end
573                 if (not match_jid) or jid:match(match_jid) then
574                         count = count + 1;
575                         print(annotate(session, { "  ", jid }));
576                 end
577         end);
578         return true, "Total: "..count.." clients";
579 end
580
581 function def_env.c2s:show_insecure(match_jid)
582         local print, count = self.session.print, 0;
583         show_c2s(function (jid, session)
584                 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
585                         count = count + 1;
586                         print(jid);
587                 end
588         end);
589         return true, "Total: "..count.." insecure client connections";
590 end
591
592 function def_env.c2s:show_secure(match_jid)
593         local print, count = self.session.print, 0;
594         show_c2s(function (jid, session)
595                 if ((not match_jid) or jid:match(match_jid)) and session.secure then
596                         count = count + 1;
597                         print(jid);
598                 end
599         end);
600         return true, "Total: "..count.." secure client connections";
601 end
602
603 function def_env.c2s:show_tls(match_jid)
604         return self:show(match_jid, tls_info);
605 end
606
607 function def_env.c2s:close(match_jid)
608         local count = 0;
609         show_c2s(function (jid, session)
610                 if jid == match_jid or jid_bare(jid) == match_jid then
611                         count = count + 1;
612                         session:close();
613                 end
614         end);
615         return true, "Total: "..count.." sessions closed";
616 end
617
618
619 def_env.s2s = {};
620 function def_env.s2s:show(match_jid, annotate)
621         local print = self.session.print;
622         annotate = annotate or session_flags;
623
624         local count_in, count_out = 0,0;
625         local s2s_list = { };
626
627         local s2s_sessions = module:shared"/*/s2s/sessions";
628         for _, session in pairs(s2s_sessions) do
629                 local remotehost, localhost, direction;
630                 if session.direction == "outgoing" then
631                         direction = "->";
632                         count_out = count_out + 1;
633                         remotehost, localhost = session.to_host or "?", session.from_host or "?";
634                 else
635                         direction = "<-";
636                         count_in = count_in + 1;
637                         remotehost, localhost = session.from_host or "?", session.to_host or "?";
638                 end
639                 local sess_lines = { l = localhost, r = remotehost,
640                         annotate(session, { "", direction, remotehost or "?" })};
641
642                 if (not match_jid) or remotehost:match(match_jid) or localhost:match(match_jid) then
643                         table.insert(s2s_list, sess_lines);
644                         local print = function (s) table.insert(sess_lines, "        "..s); end
645                         if session.sendq then
646                                 print("There are "..#session.sendq.." queued outgoing stanzas for this connection");
647                         end
648                         if session.type == "s2sout_unauthed" then
649                                 if session.connecting then
650                                         print("Connection not yet established");
651                                         if not session.srv_hosts then
652                                                 if not session.conn then
653                                                         print("We do not yet have a DNS answer for this host's SRV records");
654                                                 else
655                                                         print("This host has no SRV records, using A record instead");
656                                                 end
657                                         elseif session.srv_choice then
658                                                 print("We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
659                                                 local srv_choice = session.srv_hosts[session.srv_choice];
660                                                 print("Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
661                                         end
662                                 elseif session.notopen then
663                                         print("The <stream> has not yet been opened");
664                                 elseif not session.dialback_key then
665                                         print("Dialback has not been initiated yet");
666                                 elseif session.dialback_key then
667                                         print("Dialback has been requested, but no result received");
668                                 end
669                         end
670                         if session.type == "s2sin_unauthed" then
671                                 print("Connection not yet authenticated");
672                         elseif session.type == "s2sin" then
673                                 for name in pairs(session.hosts) do
674                                         if name ~= session.from_host then
675                                                 print("also hosts "..tostring(name));
676                                         end
677                                 end
678                         end
679                 end
680         end
681
682         -- Sort by local host, then remote host
683         table.sort(s2s_list, function(a,b)
684                 if a.l == b.l then return a.r < b.r; end
685                 return a.l < b.l;
686         end);
687         local lasthost;
688         for _, sess_lines in ipairs(s2s_list) do
689                 if sess_lines.l ~= lasthost then print(sess_lines.l); lasthost=sess_lines.l end
690                 for _, line in ipairs(sess_lines) do print(line); end
691         end
692         return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
693 end
694
695 function def_env.s2s:show_tls(match_jid)
696         return self:show(match_jid, tls_info);
697 end
698
699 local function print_subject(print, subject)
700         for _, entry in ipairs(subject) do
701                 print(
702                         ("    %s: %q"):format(
703                                 entry.name or entry.oid,
704                                 entry.value:gsub("[\r\n%z%c]", " ")
705                         )
706                 );
707         end
708 end
709
710 -- As much as it pains me to use the 0-based depths that OpenSSL does,
711 -- I think there's going to be more confusion among operators if we
712 -- break from that.
713 local function print_errors(print, errors)
714         for depth, t in pairs(errors) do
715                 print(
716                         ("    %d: %s"):format(
717                                 depth-1,
718                                 table.concat(t, "\n|        ")
719                         )
720                 );
721         end
722 end
723
724 function def_env.s2s:showcert(domain)
725         local ser = require "util.serialization".serialize;
726         local print = self.session.print;
727         local s2s_sessions = module:shared"/*/s2s/sessions";
728         local domain_sessions = set.new(array.collect(values(s2s_sessions)))
729                 /function(session) return (session.to_host == domain or session.from_host == domain) and session or nil; end;
730         local cert_set = {};
731         for session in domain_sessions do
732                 local conn = session.conn;
733                 conn = conn and conn:socket();
734                 if not conn.getpeerchain then
735                         if conn.dohandshake then
736                                 error("This version of LuaSec does not support certificate viewing");
737                         end
738                 else
739                         local cert = conn:getpeercertificate();
740                         if cert then
741                                 local certs = conn:getpeerchain();
742                                 local digest = cert:digest("sha1");
743                                 if not cert_set[digest] then
744                                         local chain_valid, chain_errors = conn:getpeerverification();
745                                         cert_set[digest] = {
746                                                 {
747                                                   from = session.from_host,
748                                                   to = session.to_host,
749                                                   direction = session.direction
750                                                 };
751                                                 chain_valid = chain_valid;
752                                                 chain_errors = chain_errors;
753                                                 certs = certs;
754                                         };
755                                 else
756                                         table.insert(cert_set[digest], {
757                                                 from = session.from_host,
758                                                 to = session.to_host,
759                                                 direction = session.direction
760                                         });
761                                 end
762                         end
763                 end
764         end
765         local domain_certs = array.collect(values(cert_set));
766         -- Phew. We now have a array of unique certificates presented by domain.
767         local n_certs = #domain_certs;
768
769         if n_certs == 0 then
770                 return "No certificates found for "..domain;
771         end
772
773         local function _capitalize_and_colon(byte)
774                 return string.upper(byte)..":";
775         end
776         local function pretty_fingerprint(hash)
777                 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
778         end
779
780         for cert_info in values(domain_certs) do
781                 local certs = cert_info.certs;
782                 local cert = certs[1];
783                 print("---")
784                 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
785                 print("");
786                 local n_streams = #cert_info;
787                 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
788                 for _, stream in ipairs(cert_info) do
789                         if stream.direction == "incoming" then
790                                 print("    "..stream.to.." <- "..stream.from);
791                         else
792                                 print("    "..stream.from.." -> "..stream.to);
793                         end
794                 end
795                 print("");
796                 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
797                 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
798                 if chain_valid then
799                         print("Trusted certificate: Yes");
800                 else
801                         print("Trusted certificate: No");
802                         print_errors(print, errors);
803                 end
804                 print("");
805                 print("Issuer: ");
806                 print_subject(print, cert:issuer());
807                 print("");
808                 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
809                 print("Subject:");
810                 print_subject(print, cert:subject());
811         end
812         print("---");
813         return ("Showing "..n_certs.." certificate"
814                 ..(n_certs==1 and "" or "s")
815                 .." presented by "..domain..".");
816 end
817
818 function def_env.s2s:close(from, to)
819         local print, count = self.session.print, 0;
820         local s2s_sessions = module:shared"/*/s2s/sessions";
821
822         local match_id;
823         if from and not to then
824                 match_id, from = from;
825         elseif not to then
826                 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
827         elseif from == to then
828                 return false, "Both from and to are the same... you can't do that :)";
829         end
830
831         for _, session in pairs(s2s_sessions) do
832                 local id = session.type..tostring(session):match("[a-f0-9]+$");
833                 if (match_id and match_id == id)
834                 or (session.from_host == from and session.to_host == to) then
835                         print(("Closing connection from %s to %s [%s]"):format(session.from_host, session.to_host, id));
836                         (session.close or s2smanager.destroy_session)(session);
837                         count = count + 1 ;
838                 end
839                         end
840         return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
841 end
842
843 function def_env.s2s:closeall(host)
844         local count = 0;
845         local s2s_sessions = module:shared"/*/s2s/sessions";
846         for _,session in pairs(s2s_sessions) do
847                 if not host or session.from_host == host or session.to_host == host then
848                         session:close();
849                                 count = count + 1;
850                         end
851                 end
852         if count == 0 then return false, "No sessions to close.";
853         else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
854 end
855
856 def_env.host = {}; def_env.hosts = def_env.host;
857
858 function def_env.host:activate(hostname, config)
859         return hostmanager.activate(hostname, config);
860 end
861 function def_env.host:deactivate(hostname, reason)
862         return hostmanager.deactivate(hostname, reason);
863 end
864
865 function def_env.host:list()
866         local print = self.session.print;
867         local i = 0;
868         local type;
869         for host in values(array.collect(keys(prosody.hosts)):sort()) do
870                 i = i + 1;
871                 type = hosts[host].type;
872                 if type == "local" then
873                         print(host);
874                 else
875                         type = module:context(host):get_option_string("component_module", type);
876                         if type ~= "component" then
877                                 type = type .. " component";
878                         end
879                         print(("%s (%s)"):format(host, type));
880                 end
881         end
882         return true, i.." hosts";
883 end
884
885 def_env.port = {};
886
887 function def_env.port:list()
888         local print = self.session.print;
889         local services = portmanager.get_active_services().data;
890         local ordered_services, n_ports = {}, 0;
891         for service, interfaces in pairs(services) do
892                 table.insert(ordered_services, service);
893         end
894         table.sort(ordered_services);
895         for _, service in ipairs(ordered_services) do
896                 local ports_list = {};
897                 for interface, ports in pairs(services[service]) do
898                         for port in pairs(ports) do
899                                 table.insert(ports_list, "["..interface.."]:"..port);
900                         end
901                 end
902                 n_ports = n_ports + #ports_list;
903                 print(service..": "..table.concat(ports_list, ", "));
904         end
905         return true, #ordered_services.." services listening on "..n_ports.." ports";
906 end
907
908 function def_env.port:close(close_port, close_interface)
909         close_port = assert(tonumber(close_port), "Invalid port number");
910         local n_closed = 0;
911         local services = portmanager.get_active_services().data;
912         for service, interfaces in pairs(services) do
913                 for interface, ports in pairs(interfaces) do
914                         if not close_interface or close_interface == interface then
915                                 if ports[close_port] then
916                                         self.session.print("Closing ["..interface.."]:"..close_port.."...");
917                                         local ok, err = portmanager.close(interface, close_port)
918                                         if not ok then
919                                                 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
920                                         else
921                                                 n_closed = n_closed + 1;
922                                         end
923                                 end
924                         end
925                 end
926         end
927         return true, "Closed "..n_closed.." ports";
928 end
929
930 def_env.muc = {};
931
932 local console_room_mt = {
933         __index = function (self, k) return self.room[k]; end;
934         __tostring = function (self)
935                 return "MUC room <"..self.room.jid..">";
936         end;
937 };
938
939 local function check_muc(jid)
940         local room_name, host = jid_split(jid);
941         if not hosts[host] then
942                 return nil, "No such host: "..host;
943         elseif not hosts[host].modules.muc then
944                 return nil, "Host '"..host.."' is not a MUC service";
945         end
946         return room_name, host;
947 end
948
949 function def_env.muc:create(room_jid)
950         local room, host = check_muc(room_jid);
951         if not room_name then
952                 return room_name, host;
953         end
954         if not room then return nil, host end
955         if hosts[host].modules.muc.rooms[room_jid] then return nil, "Room exists already" end
956         return hosts[host].modules.muc.create_room(room_jid);
957 end
958
959 function def_env.muc:room(room_jid)
960         local room_name, host = check_muc(room_jid);
961         if not room_name then
962                 return room_name, host;
963         end
964         local room_obj = hosts[host].modules.muc.rooms[room_jid];
965         if not room_obj then
966                 return nil, "No such room: "..room_jid;
967         end
968         return setmetatable({ room = room_obj }, console_room_mt);
969 end
970
971 function def_env.muc:list(host)
972         local host_session = hosts[host];
973         if not host_session or not host_session.modules.muc then
974                 return nil, "Please supply the address of a local MUC component";
975         end
976         local c = 0;
977         for name in keys(host_session.modules.muc.rooms) do
978                 print(name);
979                 c = c + 1;
980         end
981         return true, c.." rooms";
982 end
983
984 local um = require"core.usermanager";
985
986 def_env.user = {};
987 function def_env.user:create(jid, password)
988         local username, host = jid_split(jid);
989         if not hosts[host] then
990                 return nil, "No such host: "..host;
991         elseif um.user_exists(username, host) then
992                 return nil, "User exists";
993         end
994         local ok, err = um.create_user(username, password, host);
995         if ok then
996                 return true, "User created";
997         else
998                 return nil, "Could not create user: "..err;
999         end
1000 end
1001
1002 function def_env.user:delete(jid)
1003         local username, host = jid_split(jid);
1004         if not hosts[host] then
1005                 return nil, "No such host: "..host;
1006         elseif not um.user_exists(username, host) then
1007                 return nil, "No such user";
1008         end
1009         local ok, err = um.delete_user(username, host);
1010         if ok then
1011                 return true, "User deleted";
1012         else
1013                 return nil, "Could not delete user: "..err;
1014         end
1015 end
1016
1017 function def_env.user:password(jid, password)
1018         local username, host = jid_split(jid);
1019         if not hosts[host] then
1020                 return nil, "No such host: "..host;
1021         elseif not um.user_exists(username, host) then
1022                 return nil, "No such user";
1023         end
1024         local ok, err = um.set_password(username, password, host);
1025         if ok then
1026                 return true, "User password changed";
1027         else
1028                 return nil, "Could not change password for user: "..err;
1029         end
1030 end
1031
1032 function def_env.user:list(host, pat)
1033         if not host then
1034                 return nil, "No host given";
1035         elseif not hosts[host] then
1036                 return nil, "No such host";
1037         end
1038         local print = self.session.print;
1039         local total, matches = 0, 0;
1040         for user in um.users(host) do
1041                 if not pat or user:match(pat) then
1042                         print(user.."@"..host);
1043                         matches = matches + 1;
1044                 end
1045                 total = total + 1;
1046         end
1047         return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
1048 end
1049
1050 def_env.xmpp = {};
1051
1052 local st = require "util.stanza";
1053 function def_env.xmpp:ping(localhost, remotehost)
1054         if hosts[localhost] then
1055                 core_post_stanza(hosts[localhost],
1056                         st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
1057                                 :tag("ping", {xmlns="urn:xmpp:ping"}));
1058                 return true, "Sent ping";
1059         else
1060                 return nil, "No such host";
1061         end
1062 end
1063
1064 def_env.dns = {};
1065 local adns = require"net.adns";
1066 local dns = require"net.dns";
1067
1068 function def_env.dns:lookup(name, typ, class)
1069         local ret = "Query sent";
1070         local print = self.session.print;
1071         local function handler(...)
1072                 ret = "Got response";
1073                 print(...);
1074         end
1075         adns.lookup(handler, name, typ, class);
1076         return true, ret;
1077 end
1078
1079 function def_env.dns:addnameserver(...)
1080         dns._resolver:addnameserver(...)
1081         return true
1082 end
1083
1084 function def_env.dns:setnameserver(...)
1085         dns._resolver:setnameserver(...)
1086         return true
1087 end
1088
1089 function def_env.dns:purge()
1090         dns.purge()
1091         return true
1092 end
1093
1094 function def_env.dns:cache()
1095         return true, "Cache:\n"..tostring(dns.cache())
1096 end
1097
1098 -------------
1099
1100 function printbanner(session)
1101         local option = module:get_option("console_banner");
1102         if option == nil or option == "full" or option == "graphic" then
1103                 session.print [[
1104                    ____                \   /     _
1105                     |  _ \ _ __ ___  ___  _-_   __| |_   _
1106                     | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1107                     |  __/| | | (_) \__ \ |_| | (_| | |_| |
1108                     |_|   |_|  \___/|___/\___/ \__,_|\__, |
1109                     A study in simplicity            |___/
1110
1111 ]]
1112         end
1113         if option == nil or option == "short" or option == "full" then
1114         session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1115         session.print("You may find more help on using this console in our online documentation at ");
1116         session.print("http://prosody.im/doc/console\n");
1117         end
1118         if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
1119                 if type(option) == "string" then
1120                         session.print(option)
1121                 elseif type(option) == "function" then
1122                         module:log("warn", "Using functions as value for the console_banner option is no longer supported");
1123                 end
1124         end
1125 end
1126
1127 module:provides("net", {
1128         name = "console";
1129         listener = console_listener;
1130         default_port = 5582;
1131         private = true;
1132 });