File

util/iterators.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 12744:e894677359e5
line wrap: on
line source

-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--

--[[ Iterators ]]--

local it = {};

local t_insert = table.insert;
local next = next;
local unpack = table.unpack;
local pack = table.pack;
local type = type;
local table, setmetatable = table, setmetatable;

local _ENV = nil;
--luacheck: std none

-- Reverse an iterator
function it.reverse(f, s, var)
	local results = {};

	-- First call the normal iterator
	while true do
		local ret = { f(s, var) };
		var = ret[1];
		if var == nil then break; end
		t_insert(results, 1, ret);
	end

	-- Then return our reverse one
	local i,max = 0, #results;
	return function (_results)
		if i<max then
			i = i + 1;
			return unpack(_results[i]);
		end
	end, results;
end

-- Iterate only over keys in a table
local function _keys_it(t, key)
	return (next(t, key));
end
function it.keys(t)
	return _keys_it, t;
end

-- Iterate only over values in a table
function it.values(t)
	local key, val;
	return function (_t)
		key, val = next(_t, key);
		return val;
	end, t;
end

-- Iterate over the n:th return value
function it.select(n, f, s, var)
	return function (_s)
		local ret = pack(f(_s, var));
		var = ret[1];
		return ret[n];
	end, s, var;
end

-- Given an iterator, iterate only over unique items
function it.unique(f, s, var)
	local set = {};

	return function ()
		while true do
			local ret = pack(f(s, var));
			var = ret[1];
			if var == nil then break; end
			if not set[var] then
				set[var] = true;
				return unpack(ret, 1, ret.n);
			end
		end
	end;
end

--[[ Return the number of items an iterator returns ]]--
function it.count(f, s, var)
	local x = 0;

	while true do
		var = f(s, var);
		if var == nil then break; end
		x = x + 1;
	end

	return x;
end

-- Return the first n items an iterator returns
function it.head(n, f, s, var)
	local c = 0;
	return function (_s, _var)
		if c >= n then
			return nil;
		end
		c = c + 1;
		return f(_s, _var);
	end, s, var;
end

-- Skip the first n items an iterator returns
function it.skip(n, f, s, var)
	for _ = 1, n do
		var = f(s, var);
	end
	return f, s, var;
end

-- Return the last n items an iterator returns
function it.tail(n, f, s, var)
	local results, count = {}, 0;
	while true do
		local ret = pack(f(s, var));
		var = ret[1];
		if var == nil then break; end
		results[(count%n)+1] = ret;
		count = count + 1;
	end

	if n > count then n = count; end

	local pos = 0;
	return function ()
		pos = pos + 1;
		if pos > n then return nil; end
		local ret = results[((count-1+pos)%n)+1];
		return unpack(ret, 1, ret.n);
	end
	--return reverse(head(n, reverse(f, s, var))); -- !
end

function it.filter(filter, f, s, var)
	if type(filter) ~= "function" then
		local filter_value = filter;
		function filter(x) return x ~= filter_value; end
	end
	return function (_s, _var)
		local ret;
		repeat ret = pack(f(_s, _var));
			_var = ret[1];
		until _var == nil or filter(unpack(ret, 1, ret.n));
		return unpack(ret, 1, ret.n);
	end, s, var;
end

local function _ripairs_iter(t, key) if key > 1 then return key-1, t[key-1]; end end
function it.ripairs(t)
	return _ripairs_iter, t, #t+1;
end

local function _range_iter(max, curr) if curr < max then return curr + 1; end end
function it.range(x, y)
	if not y then x, y = 1, x; end -- Default to 1..x if y not given
	return _range_iter, y, x-1;
end

-- Convert the values returned by an iterator to an array
function it.to_array(f, s, var)
	local t = {};
	while true do
		var = f(s, var);
		if var == nil then break; end
		t_insert(t, var);
	end
	return t;
end

function it.sorted_pairs(t, sort_func)
	local keys = it.to_array(it.keys(t));
	table.sort(keys, sort_func);
	local i = 0;
	return function ()
		i = i + 1;
		local key = keys[i];
		if key ~= nil then
			return key, t[key];
		end
	end;
end

-- Treat the return of an iterator as key,value pairs,
-- and build a table
function it.to_table(f, s, var)
	local t, var2 = {};
	while true do
		var, var2 = f(s, var);
		if var == nil then break; end
		t[var] = var2;
	end
	return t;
end

local function _join_iter(j_s, j_var)
	local iterators, current_idx = j_s[1], j_s[2];
	local f, s, var = unpack(iterators[current_idx], 1, 3);
	if j_var ~= nil then
		var = j_var;
	end
	local ret = pack(f(s, var));
	local var1 = ret[1];
	if var1 == nil then
		-- End of this iterator, advance to next
		if current_idx == #iterators then
			-- No more iterators, return nil
			return;
		end
		j_s[2] = current_idx + 1;
		return _join_iter(j_s);
	end
	return unpack(ret, 1, ret.n);
end
local join_methods = {};
local join_mt = {
	__index = join_methods;
	__call = function (t, s, var) --luacheck: ignore 212/t
		return _join_iter(s, var);
	end;
};

function join_methods:append(f, s, var)
	table.insert(self, { f, s, var });
	return self, { self, 1 };
end

function join_methods:prepend(f, s, var)
	table.insert(self, { f, s, var }, 1);
	return self, { self, 1 };
end

function it.join(f, s, var)
	local t = setmetatable({ {f, s, var} }, join_mt);
	return t, { t, 1 };
end

return it;