Software / code / prosody
File
util/prosodyctl/shell.lua @ 13652:a08065207ef0
net.server_epoll: Call :shutdown() on TLS sockets when supported
Comment from Matthew:
This fixes a potential issue where the Prosody process gets blocked on sockets
waiting for them to close. Unlike non-TLS sockets, closing a TLS socket sends
layer 7 data, and this can cause problems for sockets which are in the process
of being cleaned up.
This depends on LuaSec changes which are not yet upstream.
From Martijn's original email:
So first my analysis of luasec. in ssl.c the socket is put into blocking
mode right before calling SSL_shutdown() inside meth_destroy(). My best
guess to why this is is because meth_destroy is linked to the __close
and __gc methods, which can't exactly be called multiple times and
luasec does want to make sure that a tls session is shutdown as clean
as possible.
I can't say I disagree with this reasoning and don't want to change this
behaviour. My solution to this without changing the current behaviour is
to introduce a shutdown() method. I am aware that this overlaps in a
conflicting way with tcp's shutdown method, but it stays close to the
OpenSSL name. This method calls SSL_shutdown() in the current
(non)blocking mode of the underlying socket and returns a boolean
whether or not the shutdown is completed (matching SSL_shutdown()'s 0
or 1 return values), and returns the familiar ssl_ioerror() strings on
error with a false for completion. This error can then be used to
determine if we have wantread/wantwrite to finalize things. Once
meth_shutdown() has been called once a shutdown flag will be set, which
indicates to meth_destroy() that the SSL_shutdown() has been handled
by the application and it shouldn't be needed to set the socket to
blocking mode. I've left the SSL_shutdown() call in the
LSEC_STATE_CONNECTED to prevent TOCTOU if the application reaches a
timeout for the shutdown code, which might allow SSL_shutdown() to
clean up anyway at the last possible moment.
Another thing I've changed to luasec is the call to socket_setblocking()
right before calling close(2) in socket_destroy() in usocket.c.
According to the latest POSIX[0]:
Note that the requirement for close() on a socket to block for up to
the current linger interval is not conditional on the O_NONBLOCK
setting.
Which I read to mean that removing O_NONBLOCK on the socket before close
doesn't impact the behaviour and only causes noise in system call
tracers. I didn't touch the windows bits of this, since I don't do
windows.
For the prosody side of things I've made the TLS shutdown bits resemble
interface:onwritable(), and put it under a combined guard of self._tls
and self.conn.shutdown. The self._tls bit is there to prevent getting
stuck on this condition, and self.conn.shutdown is there to prevent the
code being called by instances where the patched luasec isn't deployed.
The destroy() method can be called from various places and is read by
me as the "we give up" error path. To accommodate for these unexpected
entrypoints I've added a single call to self.conn:shutdown() to prevent
the socket being put into blocking mode. I have no expectations that
there is any other use here. Same as previous, the self.conn.shutdown
check is there to make sure it's not called on unpatched luasec
deployments and self._tls is there to make sure we don't call shutdown()
on tcp sockets.
I wouldn't recommend logging of the conn:shutdown() error inside
close(), since a lot of clients simply close the connection before
SSL_shutdown() is done.
| author | Martijn van Duren <martijn@openbsd.org> |
|---|---|
| date | Thu, 06 Feb 2025 15:04:38 +0000 |
| parent | 13643:e5f62871e6a5 |
| child | 13732:1465b1e305df |
line wrap: on
line source
local config = require "prosody.core.configmanager"; local human_io = require "prosody.util.human.io"; local server = require "prosody.net.server"; local st = require "prosody.util.stanza"; local path = require "prosody.util.paths"; local parse_args = require "prosody.util.argparse".parse; local tc = require "prosody.util.termcolours"; local isatty = require "prosody.util.pposix".isatty; local term_width = require"prosody.util.human.io".term_width; local have_readline, readline = pcall(require, "readline"); local adminstream = require "prosody.util.adminstream"; if have_readline then readline.set_readline_name("prosody"); readline.set_options({ histfile = path.join(prosody.paths.data, ".shell_history"); ignoredups = true; }); end local function read_line(prompt_string) if have_readline then return readline.readline(prompt_string); else io.write(prompt_string); return io.read("*line"); end end local function send_line(client, line) client.send(st.stanza("repl-input", { width = tostring(term_width()) }):text(line)); end local function repl(client) local line = read_line(client.prompt_string or "prosody> "); if not line or line == "quit" or line == "exit" or line == "bye" then if not line then print(""); end if have_readline then readline.save_history(); end os.exit(0, true); end send_line(client, line); end local function printbanner() local banner = config.get("*", "console_banner"); if banner then return print(banner); end print([[ ____ \ / _ | _ \ _ __ ___ ___ _-_ __| |_ _ | |_) | '__/ _ \/ __|/ _ \ / _` | | | | | __/| | | (_) \__ \ |_| | (_| | |_| | |_| |_| \___/|___/\___/ \__,_|\__, | A study in simplicity |___/ ]]); print("Welcome to the Prosody administration console. For a list of commands, type: help"); print("You may find more help on using this console in our online documentation at "); print("https://prosody.im/doc/console\n"); end local function check() local lfs = require "lfs"; local socket_path = path.resolve_relative_path(prosody.paths.data, config.get("*", "admin_socket") or "prosody.sock"); local state = lfs.attributes(socket_path, "mode"); return state == "socket"; end local function start(arg) --luacheck: ignore 212/arg local client = adminstream.client(); local opts, err, where = parse_args(arg); local ttyout = isatty(io.stdout); if not opts then if err == "param-not-found" then print("Unknown command-line option: "..tostring(where)); elseif err == "missing-value" then print("Expected a value to follow command-line option: "..where); end os.exit(1); end if arg[1] then if arg[2] then local fmt = { "%s"; ":%s("; ")" }; for i = 3, #arg do if arg[i]:sub(1, 1) == ":" then table.insert(fmt, i, ")%s("); elseif i > 3 and fmt[i - 1]:match("%%q$") then table.insert(fmt, i, ", %q"); else table.insert(fmt, i, "%q"); end end arg[1] = string.format(table.concat(fmt), table.unpack(arg)); end client.events.add_handler("connected", function() send_line(client, arg[1]); return true; end, 1); local errors = 0; -- TODO This is weird, but works for now. client.events.add_handler("received", function(stanza) if stanza.name == "repl-output" or stanza.name == "repl-result" then local dest = io.stdout; if stanza.attr.type == "error" then errors = errors + 1; dest = io.stderr; end if stanza.attr.eol == "0" then dest:write(stanza:get_text()); else dest:write(stanza:get_text(), "\n"); end end if stanza.name == "repl-result" then os.exit(errors); end return true; end, 1); end client.events.add_handler("connected", function () if not opts.quiet then printbanner(); end repl(client); end); client.events.add_handler("disconnected", function () print("--- session closed ---"); os.exit(0, true); end); client.events.add_handler("received", function (stanza) if stanza.name ~= "repl-request-input" then return; end if stanza.attr.type == "password" then local password = human_io.read_password(); client.send(st.stanza("repl-requested-input", { type = stanza.attr.type, id = stanza.attr.id }):text(password)); else io.stderr:write("Internal error - unexpected input request type "..tostring(stanza.attr.type).."\n"); os.exit(1); end return true; end, 2); client.events.add_handler("received", function (stanza) if stanza.name == "repl-output" or stanza.name == "repl-result" then local result_prefix = stanza.attr.type == "error" and "!" or "|"; local out = result_prefix.." "..stanza:get_text(); if ttyout and stanza.attr.type == "error" then out = tc.getstring(tc.getstyle("red"), out); end print(out); end if stanza.name == "repl-result" then repl(client); end end); client.prompt_string = config.get("*", "admin_shell_prompt"); local socket_path = path.resolve_relative_path(prosody.paths.data, opts.socket or config.get("*", "admin_socket") or "prosody.sock"); local conn = adminstream.connection(socket_path, client.listeners); local ok, err = conn:connect(); if not ok then if err == "no unix socket support" then print("** LuaSocket unix socket support not available or incompatible, ensure your"); print("** version is up to date."); else print("** Unable to connect to server - is it running? Is mod_admin_shell enabled?"); print("** Connection error: "..err); end os.exit(1); end server.loop(); end return { shell = start; available = check; };