host: properly clean up passed fds

On the service server side, i.e. the actual host service binary,
when we receive a message that contains file descriptors, clean
then up eagerly, instead relying on the garbage collector.
More importantly, the fds that we get from as a reply, if any,
need to be closed since in the current model the ownership is
transferred to the caller of `dispatch`.
This commit is contained in:
Christian Kellner 2021-09-23 20:24:25 +00:00 committed by Tom Gundersen
parent 21ad9fa399
commit 3da1db0865

View file

@ -250,17 +250,22 @@ class Service(abc.ABC):
break
try:
reply, fds = self._handle_message(msg, fds)
reply, reply_fds = self._handle_message(msg, fds)
except: # pylint: disable=bare-except
fds = None
reply_fds = None
_, val, tb = sys.exc_info()
reply = self.protocol.encode_exception(val, tb)
finally:
fds.close()
try:
self.sock.send(reply, fds=fds)
self.sock.send(reply, fds=reply_fds)
except BrokenPipeError:
break
finally:
self._close_all(reply_fds)
def _handle_message(self, msg, fds):
"""
@ -278,6 +283,17 @@ class Service(abc.ABC):
return msg, fds
@staticmethod
def _close_all(fds: Optional[List[int]]):
if not fds:
return
for fd in fds:
try:
os.close(fd)
except OSError as e:
print(f"error closing fd '{fd}': {e!s}")
class ServiceClient:
"""