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 def_env.server = {};
286
287 function def_env.server:insane_reload()
288         prosody.unlock_globals();
289         dofile "prosody"
290         prosody = _G.prosody;
291         return true, "Server reloaded";
292 end
293
294 function def_env.server:version()
295         return true, tostring(prosody.version or "unknown");
296 end
297
298 function def_env.server:uptime()
299         local t = os.time()-prosody.start_time;
300         local seconds = t%60;
301         t = (t - seconds)/60;
302         local minutes = t%60;
303         t = (t - minutes)/60;
304         local hours = t%24;
305         t = (t - hours)/24;
306         local days = t;
307         return true, string.format("This server has been running for %d day%s, %d hour%s and %d minute%s (since %s)",
308                 days, (days ~= 1 and "s") or "", hours, (hours ~= 1 and "s") or "",
309                 minutes, (minutes ~= 1 and "s") or "", os.date("%c", prosody.start_time));
310 end
311
312 function def_env.server:shutdown(reason)
313         prosody.shutdown(reason);
314         return true, "Shutdown initiated";
315 end
316
317 local function human(kb)
318         local unit = "K";
319         if kb > 1024 then
320                 kb, unit = kb/1024, "M";
321         end
322         return ("%0.2f%sB"):format(kb, unit);
323 end
324
325 function def_env.server:memory()
326         if not has_pposix or not pposix.meminfo then
327                 return true, "Lua is using "..collectgarbage("count");
328         end
329         local mem, lua_mem = pposix.meminfo(), collectgarbage("count");
330         local print = self.session.print;
331         print("Process: "..human((mem.allocated+mem.allocated_mmap)/1024));
332         print("   Used: "..human(mem.used/1024).." ("..human(lua_mem).." by Lua)");
333         print("   Free: "..human(mem.unused/1024).." ("..human(mem.returnable/1024).." returnable)");
334         return true, "OK";
335 end
336
337 def_env.module = {};
338
339 local function get_hosts_set(hosts, module)
340         if type(hosts) == "table" then
341                 if hosts[1] then
342                         return set.new(hosts);
343                 elseif hosts._items then
344                         return hosts;
345                 end
346         elseif type(hosts) == "string" then
347                 return set.new { hosts };
348         elseif hosts == nil then
349                 local mm = require "modulemanager";
350                 local hosts_set = set.new(array.collect(keys(prosody.hosts)))
351                         / function (host) return (prosody.hosts[host].type == "local" or module and mm.is_loaded(host, module)) and host or nil; end;
352                 if module and mm.get_module("*", module) then
353                         hosts_set:add("*");
354                 end
355                 return hosts_set;
356         end
357 end
358
359 function def_env.module:load(name, hosts, config)
360         local mm = require "modulemanager";
361
362         hosts = get_hosts_set(hosts);
363
364         -- Load the module for each host
365         local ok, err, count, mod = true, nil, 0, nil;
366         for host in hosts do
367                 if (not mm.is_loaded(host, name)) then
368                         mod, err = mm.load(host, name, config);
369                         if not mod then
370                                 ok = false;
371                                 if err == "global-module-already-loaded" then
372                                         if count > 0 then
373                                                 ok, err, count = true, nil, 1;
374                                         end
375                                         break;
376                                 end
377                                 self.session.print(err or "Unknown error loading module");
378                         else
379                                 count = count + 1;
380                                 self.session.print("Loaded for "..mod.module.host);
381                         end
382                 end
383         end
384
385         return ok, (ok and "Module loaded onto "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
386 end
387
388 function def_env.module:unload(name, hosts)
389         local mm = require "modulemanager";
390
391         hosts = get_hosts_set(hosts, name);
392
393         -- Unload the module for each host
394         local ok, err, count = true, nil, 0;
395         for host in hosts do
396                 if mm.is_loaded(host, name) then
397                         ok, err = mm.unload(host, name);
398                         if not ok then
399                                 ok = false;
400                                 self.session.print(err or "Unknown error unloading module");
401                         else
402                                 count = count + 1;
403                                 self.session.print("Unloaded from "..host);
404                         end
405                 end
406         end
407         return ok, (ok and "Module unloaded from "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
408 end
409
410 function def_env.module:reload(name, hosts)
411         local mm = require "modulemanager";
412
413         hosts = array.collect(get_hosts_set(hosts, name)):sort(function (a, b)
414                 if a == "*" then return true
415                 elseif b == "*" then return false
416                 else return a < b; end
417         end);
418
419         -- Reload the module for each host
420         local ok, err, count = true, nil, 0;
421         for _, host in ipairs(hosts) do
422                 if mm.is_loaded(host, name) then
423                         ok, err = mm.reload(host, name);
424                         if not ok then
425                                 ok = false;
426                                 self.session.print(err or "Unknown error reloading module");
427                         else
428                                 count = count + 1;
429                                 if ok == nil then
430                                         ok = true;
431                                 end
432                                 self.session.print("Reloaded on "..host);
433                         end
434                 end
435         end
436         return ok, (ok and "Module reloaded on "..count.." host"..(count ~= 1 and "s" or "")) or ("Last error: "..tostring(err));
437 end
438
439 function def_env.module:list(hosts)
440         if hosts == nil then
441                 hosts = array.collect(keys(prosody.hosts));
442                 table.insert(hosts, 1, "*");
443         end
444         if type(hosts) == "string" then
445                 hosts = { hosts };
446         end
447         if type(hosts) ~= "table" then
448                 return false, "Please supply a host or a list of hosts you would like to see";
449         end
450
451         local print = self.session.print;
452         for _, host in ipairs(hosts) do
453                 print((host == "*" and "Global" or host)..":");
454                 local modules = array.collect(keys(modulemanager.get_modules(host) or {})):sort();
455                 if #modules == 0 then
456                         if prosody.hosts[host] then
457                                 print("    No modules loaded");
458                         else
459                                 print("    Host not found");
460                         end
461                 else
462                         for _, name in ipairs(modules) do
463                                 print("    "..name);
464                         end
465                 end
466         end
467 end
468
469 def_env.config = {};
470 function def_env.config:load(filename, format)
471         local config_load = require "core.configmanager".load;
472         local ok, err = config_load(filename, format);
473         if not ok then
474                 return false, err or "Unknown error loading config";
475         end
476         return true, "Config loaded";
477 end
478
479 function def_env.config:get(host, section, key)
480         local config_get = require "core.configmanager".get
481         return true, tostring(config_get(host, section, key));
482 end
483
484 function def_env.config:reload()
485         local ok, err = prosody.reload_config();
486         return ok, (ok and "Config reloaded (you may need to reload modules to take effect)") or tostring(err);
487 end
488
489 local function common_info(session, line)
490         if session.id then
491                 line[#line+1] = "["..session.id.."]"
492         else
493                 line[#line+1] = "["..session.type..(tostring(session):match("%x*$")).."]"
494         end
495 end
496
497 local function session_flags(session, line)
498         line = line or {};
499         common_info(session, line);
500         if session.type == "c2s" then
501                 local status, priority = "unavailable", tostring(session.priority or "-");
502                 if session.presence then
503                         status = session.presence:get_child_text("show") or "available";
504                 end
505                 line[#line+1] = status.."("..priority..")";
506         end
507         if session.cert_identity_status == "valid" then
508                 line[#line+1] = "(authenticated)";
509         end
510         if session.secure then
511                 line[#line+1] = "(encrypted)";
512         end
513         if session.compressed then
514                 line[#line+1] = "(compressed)";
515         end
516         if session.smacks then
517                 line[#line+1] = "(sm)";
518         end
519         if session.ip and session.ip:match(":") then
520                 line[#line+1] = "(IPv6)";
521         end
522         return table.concat(line, " ");
523 end
524
525 local function tls_info(session, line)
526         line = line or {};
527         common_info(session, line);
528         if session.secure then
529                 local sock = session.conn and session.conn.socket and session.conn:socket();
530                 if sock and sock.info then
531                         local info = sock:info();
532                         line[#line+1] = ("(%s with %s)"):format(info.protocol, info.cipher);
533                 else
534                         line[#line+1] = "(cipher info unavailable)";
535                 end
536         else
537                 line[#line+1] = "(insecure)";
538         end
539         return table.concat(line, " ");
540 end
541
542 def_env.c2s = {};
543
544 local function show_c2s(callback)
545         for hostname, host in pairs(hosts) do
546                 for username, user in pairs(host.sessions or {}) do
547                         for resource, session in pairs(user.sessions or {}) do
548                                 local jid = username.."@"..hostname.."/"..resource;
549                                 callback(jid, session);
550                         end
551                 end
552         end
553 end
554
555 function def_env.c2s:count(match_jid)
556         local count = 0;
557         show_c2s(function (jid, session)
558                 if (not match_jid) or jid:match(match_jid) then
559                         count = count + 1;
560                 end
561         end);
562         return true, "Total: "..count.." clients";
563 end
564
565 function def_env.c2s:show(match_jid, annotate)
566         local print, count = self.session.print, 0;
567         annotate = annotate or session_flags;
568         local curr_host;
569         show_c2s(function (jid, session)
570                 if curr_host ~= session.host then
571                         curr_host = session.host;
572                         print(curr_host);
573                 end
574                 if (not match_jid) or jid:match(match_jid) then
575                         count = count + 1;
576                         print(annotate(session, { "  ", jid }));
577                 end
578         end);
579         return true, "Total: "..count.." clients";
580 end
581
582 function def_env.c2s:show_insecure(match_jid)
583         local print, count = self.session.print, 0;
584         show_c2s(function (jid, session)
585                 if ((not match_jid) or jid:match(match_jid)) and not session.secure then
586                         count = count + 1;
587                         print(jid);
588                 end
589         end);
590         return true, "Total: "..count.." insecure client connections";
591 end
592
593 function def_env.c2s:show_secure(match_jid)
594         local print, count = self.session.print, 0;
595         show_c2s(function (jid, session)
596                 if ((not match_jid) or jid:match(match_jid)) and session.secure then
597                         count = count + 1;
598                         print(jid);
599                 end
600         end);
601         return true, "Total: "..count.." secure client connections";
602 end
603
604 function def_env.c2s:show_tls(match_jid)
605         return self:show(match_jid, tls_info);
606 end
607
608 function def_env.c2s:close(match_jid)
609         local count = 0;
610         show_c2s(function (jid, session)
611                 if jid == match_jid or jid_bare(jid) == match_jid then
612                         count = count + 1;
613                         session:close();
614                 end
615         end);
616         return true, "Total: "..count.." sessions closed";
617 end
618
619
620 def_env.s2s = {};
621 function def_env.s2s:show(match_jid, annotate)
622         local print = self.session.print;
623         annotate = annotate or session_flags;
624
625         local count_in, count_out = 0,0;
626         local s2s_list = { };
627
628         local s2s_sessions = module:shared"/*/s2s/sessions";
629         for _, session in pairs(s2s_sessions) do
630                 local remotehost, localhost, direction;
631                 if session.direction == "outgoing" then
632                         direction = "->";
633                         count_out = count_out + 1;
634                         remotehost, localhost = session.to_host or "?", session.from_host or "?";
635                 else
636                         direction = "<-";
637                         count_in = count_in + 1;
638                         remotehost, localhost = session.from_host or "?", session.to_host or "?";
639                 end
640                 local sess_lines = { l = localhost, r = remotehost,
641                         annotate(session, { "", direction, remotehost or "?" })};
642
643                 if (not match_jid) or remotehost:match(match_jid) or localhost:match(match_jid) then
644                         table.insert(s2s_list, sess_lines);
645                         local print = function (s) table.insert(sess_lines, "        "..s); end
646                         if session.sendq then
647                                 print("There are "..#session.sendq.." queued outgoing stanzas for this connection");
648                         end
649                         if session.type == "s2sout_unauthed" then
650                                 if session.connecting then
651                                         print("Connection not yet established");
652                                         if not session.srv_hosts then
653                                                 if not session.conn then
654                                                         print("We do not yet have a DNS answer for this host's SRV records");
655                                                 else
656                                                         print("This host has no SRV records, using A record instead");
657                                                 end
658                                         elseif session.srv_choice then
659                                                 print("We are on SRV record "..session.srv_choice.." of "..#session.srv_hosts);
660                                                 local srv_choice = session.srv_hosts[session.srv_choice];
661                                                 print("Using "..(srv_choice.target or ".")..":"..(srv_choice.port or 5269));
662                                         end
663                                 elseif session.notopen then
664                                         print("The <stream> has not yet been opened");
665                                 elseif not session.dialback_key then
666                                         print("Dialback has not been initiated yet");
667                                 elseif session.dialback_key then
668                                         print("Dialback has been requested, but no result received");
669                                 end
670                         end
671                         if session.type == "s2sin_unauthed" then
672                                 print("Connection not yet authenticated");
673                         elseif session.type == "s2sin" then
674                                 for name in pairs(session.hosts) do
675                                         if name ~= session.from_host then
676                                                 print("also hosts "..tostring(name));
677                                         end
678                                 end
679                         end
680                 end
681         end
682
683         -- Sort by local host, then remote host
684         table.sort(s2s_list, function(a,b)
685                 if a.l == b.l then return a.r < b.r; end
686                 return a.l < b.l;
687         end);
688         local lasthost;
689         for _, sess_lines in ipairs(s2s_list) do
690                 if sess_lines.l ~= lasthost then print(sess_lines.l); lasthost=sess_lines.l end
691                 for _, line in ipairs(sess_lines) do print(line); end
692         end
693         return true, "Total: "..count_out.." outgoing, "..count_in.." incoming connections";
694 end
695
696 function def_env.s2s:show_tls(match_jid)
697         return self:show(match_jid, tls_info);
698 end
699
700 local function print_subject(print, subject)
701         for _, entry in ipairs(subject) do
702                 print(
703                         ("    %s: %q"):format(
704                                 entry.name or entry.oid,
705                                 entry.value:gsub("[\r\n%z%c]", " ")
706                         )
707                 );
708         end
709 end
710
711 -- As much as it pains me to use the 0-based depths that OpenSSL does,
712 -- I think there's going to be more confusion among operators if we
713 -- break from that.
714 local function print_errors(print, errors)
715         for depth, t in pairs(errors) do
716                 print(
717                         ("    %d: %s"):format(
718                                 depth-1,
719                                 table.concat(t, "\n|        ")
720                         )
721                 );
722         end
723 end
724
725 function def_env.s2s:showcert(domain)
726         local ser = require "util.serialization".serialize;
727         local print = self.session.print;
728         local s2s_sessions = module:shared"/*/s2s/sessions";
729         local domain_sessions = set.new(array.collect(values(s2s_sessions)))
730                 /function(session) return (session.to_host == domain or session.from_host == domain) and session or nil; end;
731         local cert_set = {};
732         for session in domain_sessions do
733                 local conn = session.conn;
734                 conn = conn and conn:socket();
735                 if not conn.getpeerchain then
736                         if conn.dohandshake then
737                                 error("This version of LuaSec does not support certificate viewing");
738                         end
739                 else
740                         local cert = conn:getpeercertificate();
741                         if cert then
742                                 local certs = conn:getpeerchain();
743                                 local digest = cert:digest("sha1");
744                                 if not cert_set[digest] then
745                                         local chain_valid, chain_errors = conn:getpeerverification();
746                                         cert_set[digest] = {
747                                                 {
748                                                   from = session.from_host,
749                                                   to = session.to_host,
750                                                   direction = session.direction
751                                                 };
752                                                 chain_valid = chain_valid;
753                                                 chain_errors = chain_errors;
754                                                 certs = certs;
755                                         };
756                                 else
757                                         table.insert(cert_set[digest], {
758                                                 from = session.from_host,
759                                                 to = session.to_host,
760                                                 direction = session.direction
761                                         });
762                                 end
763                         end
764                 end
765         end
766         local domain_certs = array.collect(values(cert_set));
767         -- Phew. We now have a array of unique certificates presented by domain.
768         local n_certs = #domain_certs;
769
770         if n_certs == 0 then
771                 return "No certificates found for "..domain;
772         end
773
774         local function _capitalize_and_colon(byte)
775                 return string.upper(byte)..":";
776         end
777         local function pretty_fingerprint(hash)
778                 return hash:gsub("..", _capitalize_and_colon):sub(1, -2);
779         end
780
781         for cert_info in values(domain_certs) do
782                 local certs = cert_info.certs;
783                 local cert = certs[1];
784                 print("---")
785                 print("Fingerprint (SHA1): "..pretty_fingerprint(cert:digest("sha1")));
786                 print("");
787                 local n_streams = #cert_info;
788                 print("Currently used on "..n_streams.." stream"..(n_streams==1 and "" or "s")..":");
789                 for _, stream in ipairs(cert_info) do
790                         if stream.direction == "incoming" then
791                                 print("    "..stream.to.." <- "..stream.from);
792                         else
793                                 print("    "..stream.from.." -> "..stream.to);
794                         end
795                 end
796                 print("");
797                 local chain_valid, errors = cert_info.chain_valid, cert_info.chain_errors;
798                 local valid_identity = cert_verify_identity(domain, "xmpp-server", cert);
799                 if chain_valid then
800                         print("Trusted certificate: Yes");
801                 else
802                         print("Trusted certificate: No");
803                         print_errors(print, errors);
804                 end
805                 print("");
806                 print("Issuer: ");
807                 print_subject(print, cert:issuer());
808                 print("");
809                 print("Valid for "..domain..": "..(valid_identity and "Yes" or "No"));
810                 print("Subject:");
811                 print_subject(print, cert:subject());
812         end
813         print("---");
814         return ("Showing "..n_certs.." certificate"
815                 ..(n_certs==1 and "" or "s")
816                 .." presented by "..domain..".");
817 end
818
819 function def_env.s2s:close(from, to)
820         local print, count = self.session.print, 0;
821         local s2s_sessions = module:shared"/*/s2s/sessions";
822
823         local match_id;
824         if from and not to then
825                 match_id, from = from;
826         elseif not to then
827                 return false, "Syntax: s2s:close('from', 'to') - Closes all s2s sessions from 'from' to 'to'";
828         elseif from == to then
829                 return false, "Both from and to are the same... you can't do that :)";
830         end
831
832         for _, session in pairs(s2s_sessions) do
833                 local id = session.type..tostring(session):match("[a-f0-9]+$");
834                 if (match_id and match_id == id)
835                 or (session.from_host == from and session.to_host == to) then
836                         print(("Closing connection from %s to %s [%s]"):format(session.from_host, session.to_host, id));
837                         (session.close or s2smanager.destroy_session)(session);
838                         count = count + 1 ;
839                 end
840                         end
841         return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s");
842 end
843
844 function def_env.s2s:closeall(host)
845         local count = 0;
846         local s2s_sessions = module:shared"/*/s2s/sessions";
847         for _,session in pairs(s2s_sessions) do
848                 if not host or session.from_host == host or session.to_host == host then
849                         session:close();
850                                 count = count + 1;
851                         end
852                 end
853         if count == 0 then return false, "No sessions to close.";
854         else return true, "Closed "..count.." s2s session"..((count == 1 and "") or "s"); end
855 end
856
857 def_env.host = {}; def_env.hosts = def_env.host;
858
859 function def_env.host:activate(hostname, config)
860         return hostmanager.activate(hostname, config);
861 end
862 function def_env.host:deactivate(hostname, reason)
863         return hostmanager.deactivate(hostname, reason);
864 end
865
866 function def_env.host:list()
867         local print = self.session.print;
868         local i = 0;
869         local type;
870         for host in values(array.collect(keys(prosody.hosts)):sort()) do
871                 i = i + 1;
872                 type = hosts[host].type;
873                 if type == "local" then
874                         print(host);
875                 else
876                         type = module:context(host):get_option_string("component_module", type);
877                         if type ~= "component" then
878                                 type = type .. " component";
879                         end
880                         print(("%s (%s)"):format(host, type));
881                 end
882         end
883         return true, i.." hosts";
884 end
885
886 def_env.port = {};
887
888 function def_env.port:list()
889         local print = self.session.print;
890         local services = portmanager.get_active_services().data;
891         local ordered_services, n_ports = {}, 0;
892         for service, interfaces in pairs(services) do
893                 table.insert(ordered_services, service);
894         end
895         table.sort(ordered_services);
896         for _, service in ipairs(ordered_services) do
897                 local ports_list = {};
898                 for interface, ports in pairs(services[service]) do
899                         for port in pairs(ports) do
900                                 table.insert(ports_list, "["..interface.."]:"..port);
901                         end
902                 end
903                 n_ports = n_ports + #ports_list;
904                 print(service..": "..table.concat(ports_list, ", "));
905         end
906         return true, #ordered_services.." services listening on "..n_ports.." ports";
907 end
908
909 function def_env.port:close(close_port, close_interface)
910         close_port = assert(tonumber(close_port), "Invalid port number");
911         local n_closed = 0;
912         local services = portmanager.get_active_services().data;
913         for service, interfaces in pairs(services) do
914                 for interface, ports in pairs(interfaces) do
915                         if not close_interface or close_interface == interface then
916                                 if ports[close_port] then
917                                         self.session.print("Closing ["..interface.."]:"..close_port.."...");
918                                         local ok, err = portmanager.close(interface, close_port)
919                                         if not ok then
920                                                 self.session.print("Failed to close "..interface.." "..close_port..": "..err);
921                                         else
922                                                 n_closed = n_closed + 1;
923                                         end
924                                 end
925                         end
926                 end
927         end
928         return true, "Closed "..n_closed.." ports";
929 end
930
931 def_env.muc = {};
932
933 local console_room_mt = {
934         __index = function (self, k) return self.room[k]; end;
935         __tostring = function (self)
936                 return "MUC room <"..self.room.jid..">";
937         end;
938 };
939
940 local function check_muc(jid)
941         local room_name, host = jid_split(jid);
942         if not hosts[host] then
943                 return nil, "No such host: "..host;
944         elseif not hosts[host].modules.muc then
945                 return nil, "Host '"..host.."' is not a MUC service";
946         end
947         return room_name, host;
948 end
949
950 function def_env.muc:create(room_jid)
951         local room, host = check_muc(room_jid);
952         if not room_name then
953                 return room_name, host;
954         end
955         if not room then return nil, host end
956         if hosts[host].modules.muc.rooms[room_jid] then return nil, "Room exists already" end
957         return hosts[host].modules.muc.create_room(room_jid);
958 end
959
960 function def_env.muc:room(room_jid)
961         local room_name, host = check_muc(room_jid);
962         if not room_name then
963                 return room_name, host;
964         end
965         local room_obj = hosts[host].modules.muc.rooms[room_jid];
966         if not room_obj then
967                 return nil, "No such room: "..room_jid;
968         end
969         return setmetatable({ room = room_obj }, console_room_mt);
970 end
971
972 function def_env.muc:list(host)
973         local host_session = hosts[host];
974         if not host_session or not host_session.modules.muc then
975                 return nil, "Please supply the address of a local MUC component";
976         end
977         local print = self.session.print;
978         local c = 0;
979         for name in keys(host_session.modules.muc.rooms) do
980                 print(name);
981                 c = c + 1;
982         end
983         return true, c.." rooms";
984 end
985
986 local um = require"core.usermanager";
987
988 def_env.user = {};
989 function def_env.user:create(jid, password)
990         local username, host = jid_split(jid);
991         if not hosts[host] then
992                 return nil, "No such host: "..host;
993         elseif um.user_exists(username, host) then
994                 return nil, "User exists";
995         end
996         local ok, err = um.create_user(username, password, host);
997         if ok then
998                 return true, "User created";
999         else
1000                 return nil, "Could not create user: "..err;
1001         end
1002 end
1003
1004 function def_env.user:delete(jid)
1005         local username, host = jid_split(jid);
1006         if not hosts[host] then
1007                 return nil, "No such host: "..host;
1008         elseif not um.user_exists(username, host) then
1009                 return nil, "No such user";
1010         end
1011         local ok, err = um.delete_user(username, host);
1012         if ok then
1013                 return true, "User deleted";
1014         else
1015                 return nil, "Could not delete user: "..err;
1016         end
1017 end
1018
1019 function def_env.user:password(jid, password)
1020         local username, host = jid_split(jid);
1021         if not hosts[host] then
1022                 return nil, "No such host: "..host;
1023         elseif not um.user_exists(username, host) then
1024                 return nil, "No such user";
1025         end
1026         local ok, err = um.set_password(username, password, host);
1027         if ok then
1028                 return true, "User password changed";
1029         else
1030                 return nil, "Could not change password for user: "..err;
1031         end
1032 end
1033
1034 function def_env.user:list(host, pat)
1035         if not host then
1036                 return nil, "No host given";
1037         elseif not hosts[host] then
1038                 return nil, "No such host";
1039         end
1040         local print = self.session.print;
1041         local total, matches = 0, 0;
1042         for user in um.users(host) do
1043                 if not pat or user:match(pat) then
1044                         print(user.."@"..host);
1045                         matches = matches + 1;
1046                 end
1047                 total = total + 1;
1048         end
1049         return true, "Showing "..(pat and (matches.." of ") or "all " )..total.." users";
1050 end
1051
1052 def_env.xmpp = {};
1053
1054 local st = require "util.stanza";
1055 function def_env.xmpp:ping(localhost, remotehost)
1056         if hosts[localhost] then
1057                 core_post_stanza(hosts[localhost],
1058                         st.iq{ from=localhost, to=remotehost, type="get", id="ping" }
1059                                 :tag("ping", {xmlns="urn:xmpp:ping"}));
1060                 return true, "Sent ping";
1061         else
1062                 return nil, "No such host";
1063         end
1064 end
1065
1066 def_env.dns = {};
1067 local adns = require"net.adns";
1068 local dns = require"net.dns";
1069
1070 function def_env.dns:lookup(name, typ, class)
1071         local ret = "Query sent";
1072         local print = self.session.print;
1073         local function handler(...)
1074                 ret = "Got response";
1075                 print(...);
1076         end
1077         adns.lookup(handler, name, typ, class);
1078         return true, ret;
1079 end
1080
1081 function def_env.dns:addnameserver(...)
1082         dns._resolver:addnameserver(...)
1083         return true
1084 end
1085
1086 function def_env.dns:setnameserver(...)
1087         dns._resolver:setnameserver(...)
1088         return true
1089 end
1090
1091 function def_env.dns:purge()
1092         dns.purge()
1093         return true
1094 end
1095
1096 function def_env.dns:cache()
1097         return true, "Cache:\n"..tostring(dns.cache())
1098 end
1099
1100 -------------
1101
1102 function printbanner(session)
1103         local option = module:get_option("console_banner");
1104         if option == nil or option == "full" or option == "graphic" then
1105                 session.print [[
1106                    ____                \   /     _
1107                     |  _ \ _ __ ___  ___  _-_   __| |_   _
1108                     | |_) | '__/ _ \/ __|/ _ \ / _` | | | |
1109                     |  __/| | | (_) \__ \ |_| | (_| | |_| |
1110                     |_|   |_|  \___/|___/\___/ \__,_|\__, |
1111                     A study in simplicity            |___/
1112
1113 ]]
1114         end
1115         if option == nil or option == "short" or option == "full" then
1116         session.print("Welcome to the Prosody administration console. For a list of commands, type: help");
1117         session.print("You may find more help on using this console in our online documentation at ");
1118         session.print("http://prosody.im/doc/console\n");
1119         end
1120         if option and option ~= "short" and option ~= "full" and option ~= "graphic" then
1121                 if type(option) == "string" then
1122                         session.print(option)
1123                 elseif type(option) == "function" then
1124                         module:log("warn", "Using functions as value for the console_banner option is no longer supported");
1125                 end
1126         end
1127 end
1128
1129 module:provides("net", {
1130         name = "console";
1131         listener = console_listener;
1132         default_port = 5582;
1133         private = true;
1134 });