From fcf3ec4502e8eff88c76ad377b3760c368af94c9 Mon Sep 17 00:00:00 2001 From: Christian Kellner Date: Sat, 25 Jul 2020 14:50:34 +0200 Subject: [PATCH] jsoncomm: add connection oriented methods Implement `accept` and `listen`, that call the equivalent methods on the underlying socket; this prepares the move to a connection oriented socket, i.e. `SOCK_SEQPACKET`. --- osbuild/util/jsoncomm.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/osbuild/util/jsoncomm.py b/osbuild/util/jsoncomm.py index a3a04a77..59dbc33f 100644 --- a/osbuild/util/jsoncomm.py +++ b/osbuild/util/jsoncomm.py @@ -129,6 +129,32 @@ class Socket(contextlib.AbstractContextManager): """Set the blocking mode of the socket.""" self._socket.setblocking(value) + def accept(self) -> Optional["Socket"]: + """Accept a new connection on the socket. + + See python's `socket.accept` for more information. + """ + # Since, in the kernel, for AF_UNIX, new connection requests, + # i.e. clients connecting, are directly put on the receive + # queue of the listener socket, accept here *should* always + # return a socket and not block, even if the client meanwhile + # disconnected; we don't rely on that kernel behavior though + try: + conn, _ = self._socket.accept() + except (socket.timeout, BlockingIOError): + return None + return Socket(conn, None) + + def listen(self, backlog: Optional[int] = 2**16): + """Enable accepting of incoming connections. + + See python's `socket.listen` for details. + """ + + # `Socket.listen` accepts an `int` or no argument, but not `None` + args = [backlog] if backlog is not None else [] + self._socket.listen(*args) + def close(self): """Close Socket