File

spec/util_xmppstream_spec.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 9021:548ba4090012
line wrap: on
line source


local xmppstream = require "util.xmppstream";

describe("util.xmppstream", function()
	local function test(xml, expect_success, ex)
		local stanzas = {};
		local session = { notopen = true };
		local callbacks = {
			stream_ns = "streamns";
			stream_tag = "stream";
			default_ns = "stanzans";
			streamopened = function (_session)
				assert.are.equal(session, _session);
				assert.are.equal(session.notopen, true);
				_session.notopen = nil;
				return true;
			end;
			handlestanza = function (_session, stanza)
				assert.are.equal(session, _session);
				assert.are.equal(_session.notopen, nil);
				table.insert(stanzas, stanza);
			end;
			streamclosed = function (_session)
				assert.are.equal(session, _session);
				assert.are.equal(_session.notopen, nil);
				_session.notopen = nil;
			end;
		}
		if type(ex) == "table" then
			for k, v in pairs(ex) do
				if k ~= "_size_limit" then
					callbacks[k] = v;
				end
			end
		end
		local stream = xmppstream.new(session, callbacks, ex and ex._size_limit or nil);
		local ok, err = pcall(function ()
			assert(stream:feed(xml));
		end);

		if ok and type(expect_success) == "function" then
			expect_success(stanzas);
		end
		assert.are.equal(not not ok, not not expect_success, "Expected "..(expect_success and ("success ("..tostring(err)..")") or "failure"));
	end

	local function test_stanza(stanza, expect_success, ex)
		return test([[<stream:stream xmlns:stream="streamns" xmlns="stanzans">]]..stanza, expect_success, ex);
	end

	describe("#new()", function()
		it("should work", function()
			test([[<stream:stream xmlns:stream="streamns"/>]], true);
			test([[<stream xmlns="streamns"/>]], true);

			-- Incorrect stream tag name should be rejected
			test([[<stream1 xmlns="streamns"/>]], false);
			-- Incorrect stream namespace should be rejected
			test([[<stream xmlns="streamns1"/>]], false);
			-- Invalid XML should be rejected
			test("<>", false);

			test_stanza("<message/>", function (stanzas)
				assert.are.equal(#stanzas, 1);
				assert.are.equal(stanzas[1].name, "message");
			end);
			test_stanza("< message>>>>/>\n", false);

			test_stanza([[<x xmlns:a="b">
				<y xmlns:a="c">
					<a:z/>
				</y>
				<a:z/>
			</x>]], function (stanzas)
				assert.are.equal(#stanzas, 1);
				local s = stanzas[1];
				assert.are.equal(s.name, "x");
				assert.are.equal(#s.tags, 2);

				assert.are.equal(s.tags[1].name, "y");
				assert.are.equal(s.tags[1].attr.xmlns, nil);

				assert.are.equal(s.tags[1].tags[1].name, "z");
				assert.are.equal(s.tags[1].tags[1].attr.xmlns, "c");

				assert.are.equal(s.tags[2].name, "z");
				assert.are.equal(s.tags[2].attr.xmlns, "b");

				assert.are.equal(s.namespaces, nil);
			end);
		end);
	end);

	it("should allow an XML declaration", function ()
		test([[<?xml version="1.0" encoding="UTF-8"?><stream xmlns="streamns"/>]], true);
		test([[<?xml version="1.0" encoding="UTF-8" standalone="yes" ?><stream xmlns="streamns"/>]], true);
		test([[<?xml version="1.0" encoding="utf-8" ?><stream xmlns="streamns"/>]], true);
	end);

	it("should not accept XML versions other than 1.0", function ()
		test([[<?xml version="1.1" encoding="utf-8" ?><stream xmlns="streamns"/>]], false);
	end);

	it("should not allow a misplaced XML declaration", function ()
		test([[<stream xmlns="streamns"><?xml version="1.0" encoding="UTF-8"?></stream>]], false);
	end);

	describe("should forbid restricted XML:", function ()
		it("comments", function ()
			test_stanza("<!-- hello world -->", false);
		end);
		it("DOCTYPE", function ()
			test([[<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE stream SYSTEM "mydtd.dtd">]], false);
		end);
		it("incorrect encoding specification", function ()
			-- This is actually caught by the underlying XML parser
			test([[<?xml version="1.0" encoding="UTF-16"?><stream xmlns="streamns"/>]], false);
		end);
		it("non-UTF8 encodings: ISO-8859-1", function ()
			test([[<?xml version="1.0" encoding="ISO-8859-1"?><stream xmlns="streamns"/>]], false);
		end);
		it("non-UTF8 encodings: UTF-16", function ()
			-- <?xml version="1.0" encoding="UTF-16"?><stream xmlns="streamns"/>
			-- encoded into UTF-16
			local hx = ([[fffe3c003f0078006d006c002000760065007200730069006f006e003d00
			220031002e0030002200200065006e0063006f00640069006e0067003d00
			22005500540046002d003100360022003f003e003c007300740072006500
			61006d00200078006d006c006e0073003d00220073007400720065006100
			6d006e00730022002f003e00]]):gsub("%x%x", function (c) return string.char(tonumber(c, 16)); end);
			test(hx, false);
		end);
		it("processing instructions", function ()
			test([[<stream xmlns="streamns"><?xml-stylesheet type="text/xsl" href="style.xsl"?></stream>]], false);
		end);
	end);
end);