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