We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Restarting Qtile leaves a traceback
Traceback (most recent call last):
  File "/usr/lib/python3.7/site-packages/libqtile/ipc.py", line 72, in unpack
    assert len(data) >= HDRLEN
AssertionError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/bin/qtile-cmd", line 11, in <module>
    load_entry_point('qtile==0.14.2', 'console_scripts', 'qtile-cmd')()
  File "/usr/lib/python3.7/site-packages/libqtile/scripts/qtile_cmd.py", line 185, in main
    ret = run_function(obj, args.function[0], args.args)
  File "/usr/lib/python3.7/site-packages/libqtile/scripts/qtile_cmd.py", line 130, in run_function
    ret = func(*args)
  File "/usr/lib/python3.7/site-packages/libqtile/command.py", line 114, in __call__
    return self.call(self.selectors, self.name, *args, **kwargs)
  File "/usr/lib/python3.7/site-packages/libqtile/command.py", line 251, in call
    state, val = self.client.call((selectors, name, args, kwargs))
  File "/usr/lib/python3.7/site-packages/libqtile/ipc.py", line 213, in call
    return self.send(data)
  File "/usr/lib/python3.7/site-packages/libqtile/ipc.py", line 206, in send
    self.loop.run_until_complete(asyncio.wait_for(client_proto.reply, timeout=10))
  File "/usr/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
    return future.result()
  File "/usr/lib/python3.7/asyncio/tasks.py", line 416, in wait_for
    return fut.result()
  File "/usr/lib/python3.7/site-packages/libqtile/ipc.py", line 152, in eof_received
    data, _ = _IPC.unpack(self.recv)
  File "/usr/lib/python3.7/site-packages/libqtile/ipc.py", line 78, in unpack
    "error reading reply!"
libqtile.ipc.IPCError: error readin

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `libqtile/ipc.py`
Content:
```
1 # Copyright (c) 2008, Aldo Cortesi. All rights reserved.
2 #
3 # Permission is hereby granted, free of charge, to any person obtaining a copy
4 # of this software and associated documentation files (the "Software"), to deal
5 # in the Software without restriction, including without limitation the rights
6 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 # copies of the Software, and to permit persons to whom the Software is
8 # furnished to do so, subject to the following conditions:
9 #
10 # The above copyright notice and this permission notice shall be included in
11 # all copies or substantial portions of the Software.
12 #
13 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 # SOFTWARE.
20 
21 """
22     A simple IPC mechanism for communicating between two local processes. We
23     use marshal to serialize data - this means that both client and server must
24     run the same Python version, and that clients must be trusted (as
25     un-marshalling untrusted data can result in arbitrary code execution).
26 """
27 import asyncio
28 import fcntl
29 import json
30 import marshal
31 import os.path
32 import socket
33 import struct
34 from typing import Any, Optional, Tuple
35 
36 from libqtile.log_utils import logger
37 from libqtile.utils import get_cache_dir
38 
39 HDRFORMAT = "!L"
40 HDRLEN = struct.calcsize(HDRFORMAT)
41 
42 SOCKBASE = "qtilesocket.%s"
43 
44 
45 def find_sockfile(display: str = None):
46     """Finds the appropriate socket file for the given display"""
47     display = display or os.environ.get("DISPLAY") or ":0.0"
48     if "." not in display:
49         display += ".0"
50     cache_directory = get_cache_dir()
51     return os.path.join(cache_directory, SOCKBASE % display)
52 
53 
54 class IPCError(Exception):
55     pass
56 
57 
58 class _IPC:
59     """A helper class to handle properly packing and unpacking messages"""
60 
61     @staticmethod
62     def unpack(data: bytes, *, is_json: Optional[bool] = None) -> Tuple[Any, bool]:
63         """Unpack the incoming message
64 
65         Parameters
66         ----------
67         data : bytes
68             The incoming message to unpack
69         is_json : Optional[bool]
70             If the message should be unpacked as json.  By default, try to
71             unpack json and fallback gracefully to marshalled bytes.
72 
73         Returns
74         -------
75         Tuple[Any, bool]
76             A tuple of the unpacked object and a boolean denoting if the
77             message was deserialized using json.  If True, the return message
78             should be packed as json.
79         """
80         if is_json is None or is_json:
81             try:
82                 return json.loads(data.decode()), True
83             except ValueError as e:
84                 if is_json:
85                     raise IPCError("Unable to decode json data") from e
86 
87         try:
88             assert len(data) >= HDRLEN
89             size = struct.unpack(HDRFORMAT, data[:HDRLEN])[0]
90             assert size >= len(data[HDRLEN:])
91             return marshal.loads(data[HDRLEN:HDRLEN + size]), False
92         except AssertionError as e:
93             raise IPCError(
94                 "error reading reply! (probably the socket was disconnected)"
95             ) from e
96 
97     @staticmethod
98     def pack(msg: Any, *, is_json: bool = False) -> bytes:
99         """Pack the object into a message to pass"""
100         if is_json:
101             json_obj = json.dumps(msg)
102             return json_obj.encode()
103 
104         msg_bytes = marshal.dumps(msg)
105         size = struct.pack(HDRFORMAT, len(msg_bytes))
106         return size + msg_bytes
107 
108 
109 class Client:
110     def __init__(self, fname: str, is_json=False) -> None:
111         """Create a new IPC client
112 
113         Parameters
114         ----------
115         fname : str
116             The file path to the file that is used to open the connection to
117             the running IPC server.
118         is_json : bool
119             Pack and unpack messages as json
120         """
121         self.fname = fname
122         self.loop = asyncio.get_event_loop()
123         self.is_json = is_json
124 
125     def call(self, data: Any) -> Any:
126         return self.send(data)
127 
128     def send(self, msg: Any) -> Any:
129         """Send the message and return the response from the server
130 
131         If any exception is raised by the server, that will propogate out of
132         this call.
133         """
134         return self.loop.run_until_complete(self.async_send(msg))
135 
136     async def async_send(self, msg: Any) -> Any:
137         """Send the message to the server
138 
139         Connect to the server, then pack and send the message to the server,
140         then wait for and return the response from the server.
141         """
142         try:
143             reader, writer = await asyncio.wait_for(
144                 asyncio.open_unix_connection(path=self.fname), timeout=3
145             )
146         except (ConnectionRefusedError, FileNotFoundError):
147             raise IPCError("Could not open {}".format(self.fname))
148 
149         try:
150             send_data = _IPC.pack(msg, is_json=self.is_json)
151             writer.write(send_data)
152             writer.write_eof()
153 
154             read_data = await asyncio.wait_for(reader.read(), timeout=10)
155         except asyncio.TimeoutError:
156             raise IPCError("Server not responding")
157         finally:
158             # see the note in Server._server_callback()
159             writer.close()
160             await writer.wait_closed()
161 
162         data, _ = _IPC.unpack(read_data, is_json=self.is_json)
163 
164         return data
165 
166 
167 class Server:
168     def __init__(self, fname: str, handler) -> None:
169         self.fname = fname
170         self.handler = handler
171         self.server = None  # type: Optional[asyncio.AbstractServer]
172 
173         if os.path.exists(fname):
174             os.unlink(fname)
175 
176         self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
177         flags = fcntl.fcntl(self.sock.fileno(), fcntl.F_GETFD)
178         fcntl.fcntl(self.sock.fileno(), fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
179         self.sock.bind(self.fname)
180 
181     async def _server_callback(
182         self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
183     ) -> None:
184         """Callback when a connection is made to the server
185 
186         Read the data sent from the client, execute the requested command, and
187         send the reply back to the client.
188         """
189         try:
190             logger.debug("Connection made to server")
191             data = await reader.read()
192             logger.debug("EOF received by server")
193 
194             req, is_json = _IPC.unpack(data)
195         except IPCError:
196             logger.warn("Invalid data received, closing connection")
197         else:
198             if req[1] == "restart":
199                 # if we are going to restart, close the connection first, as we won't be back
200                 logger.debug("Closing connection on restart")
201                 writer.write_eof()
202 
203             rep = self.handler(req)
204 
205             result = _IPC.pack(rep, is_json=is_json)
206 
207             logger.debug("Sending result on receive EOF")
208             writer.write(result)
209             logger.debug("Closing connection on receive EOF")
210             writer.write_eof()
211         finally:
212             writer.close()
213             await writer.wait_closed()
214 
215     async def __aenter__(self) -> "Server":
216         """Start and return the server"""
217         await self.start()
218         return self
219 
220     async def __aexit__(self, exc_type, exc_value, tb) -> None:
221         """Close and shutdown the server"""
222         await self.close()
223 
224     async def start(self) -> None:
225         """Start the server"""
226         assert self.server is None
227 
228         logger.debug("Starting server")
229         server_coroutine = asyncio.start_unix_server(
230             self._server_callback, sock=self.sock
231         )
232         self.server = await server_coroutine
233 
234     async def close(self) -> None:
235         """Close and shutdown the server"""
236         assert self.server is not None
237 
238         logger.debug("Stopping server on close")
239         self.server.close()
240         await self.server.wait_closed()
241 
242         self.server = None
243
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/libqtile/ipc.py b/libqtile/ipc.py
--- a/libqtile/ipc.py
+++ b/libqtile/ipc.py
@@ -195,11 +195,6 @@
         except IPCError:
             logger.warn("Invalid data received, closing connection")
         else:
-            if req[1] == "restart":
-                # if we are going to restart, close the connection first, as we won't be back
-                logger.debug("Closing connection on restart")
-                writer.write_eof()
-
             rep = self.handler(req)
 
             result = _IPC.pack(rep, is_json=is_json)

{"golden_diff": "diff --git a/libqtile/ipc.py b/libqtile/ipc.py\n--- a/libqtile/ipc.py\n+++ b/libqtile/ipc.py\n@@ -195,11 +195,6 @@\n         except IPCError:\n             logger.warn(\"Invalid data received, closing connection\")\n         else:\n-            if req[1] == \"restart\":\n-                # if we are going to restart, close the connection first, as we won't be back\n-                logger.debug(\"Closing connection on restart\")\n-                writer.write_eof()\n-\n             rep = self.handler(req)\n \n             result = _IPC.pack(rep, is_json=is_json)\n", "issue": "Restarting Qtile leaves a traceback\nTraceback (most recent call last):\r\n  File \"/usr/lib/python3.7/site-packages/libqtile/ipc.py\", line 72, in unpack\r\n    assert len(data) >= HDRLEN\r\nAssertionError\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n  File \"/usr/bin/qtile-cmd\", line 11, in <module>\r\n    load_entry_point('qtile==0.14.2', 'console_scripts', 'qtile-cmd')()\r\n  File \"/usr/lib/python3.7/site-packages/libqtile/scripts/qtile_cmd.py\", line 185, in main\r\n    ret = run_function(obj, args.function[0], args.args)\r\n  File \"/usr/lib/python3.7/site-packages/libqtile/scripts/qtile_cmd.py\", line 130, in run_function\r\n    ret = func(*args)\r\n  File \"/usr/lib/python3.7/site-packages/libqtile/command.py\", line 114, in __call__\r\n    return self.call(self.selectors, self.name, *args, **kwargs)\r\n  File \"/usr/lib/python3.7/site-packages/libqtile/command.py\", line 251, in call\r\n    state, val = self.client.call((selectors, name, args, kwargs))\r\n  File \"/usr/lib/python3.7/site-packages/libqtile/ipc.py\", line 213, in call\r\n    return self.send(data)\r\n  File \"/usr/lib/python3.7/site-packages/libqtile/ipc.py\", line 206, in send\r\n    self.loop.run_until_complete(asyncio.wait_for(client_proto.reply, timeout=10))\r\n  File \"/usr/lib/python3.7/asyncio/base_events.py\", line 584, in run_until_complete\r\n    return future.result()\r\n  File \"/usr/lib/python3.7/asyncio/tasks.py\", line 416, in wait_for\r\n    return fut.result()\r\n  File \"/usr/lib/python3.7/site-packages/libqtile/ipc.py\", line 152, in eof_received\r\n    data, _ = _IPC.unpack(self.recv)\r\n  File \"/usr/lib/python3.7/site-packages/libqtile/ipc.py\", line 78, in unpack\r\n    \"error reading reply!\"\r\nlibqtile.ipc.IPCError: error readin\n", "before_files": [{"content": "# Copyright (c) 2008, Aldo Cortesi. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\n    A simple IPC mechanism for communicating between two local processes. We\n    use marshal to serialize data - this means that both client and server must\n    run the same Python version, and that clients must be trusted (as\n    un-marshalling untrusted data can result in arbitrary code execution).\n\"\"\"\nimport asyncio\nimport fcntl\nimport json\nimport marshal\nimport os.path\nimport socket\nimport struct\nfrom typing import Any, Optional, Tuple\n\nfrom libqtile.log_utils import logger\nfrom libqtile.utils import get_cache_dir\n\nHDRFORMAT = \"!L\"\nHDRLEN = struct.calcsize(HDRFORMAT)\n\nSOCKBASE = \"qtilesocket.%s\"\n\n\ndef find_sockfile(display: str = None):\n    \"\"\"Finds the appropriate socket file for the given display\"\"\"\n    display = display or os.environ.get(\"DISPLAY\") or \":0.0\"\n    if \".\" not in display:\n        display += \".0\"\n    cache_directory = get_cache_dir()\n    return os.path.join(cache_directory, SOCKBASE % display)\n\n\nclass IPCError(Exception):\n    pass\n\n\nclass _IPC:\n    \"\"\"A helper class to handle properly packing and unpacking messages\"\"\"\n\n    @staticmethod\n    def unpack(data: bytes, *, is_json: Optional[bool] = None) -> Tuple[Any, bool]:\n        \"\"\"Unpack the incoming message\n\n        Parameters\n        ----------\n        data : bytes\n            The incoming message to unpack\n        is_json : Optional[bool]\n            If the message should be unpacked as json.  By default, try to\n            unpack json and fallback gracefully to marshalled bytes.\n\n        Returns\n        -------\n        Tuple[Any, bool]\n            A tuple of the unpacked object and a boolean denoting if the\n            message was deserialized using json.  If True, the return message\n            should be packed as json.\n        \"\"\"\n        if is_json is None or is_json:\n            try:\n                return json.loads(data.decode()), True\n            except ValueError as e:\n                if is_json:\n                    raise IPCError(\"Unable to decode json data\") from e\n\n        try:\n            assert len(data) >= HDRLEN\n            size = struct.unpack(HDRFORMAT, data[:HDRLEN])[0]\n            assert size >= len(data[HDRLEN:])\n            return marshal.loads(data[HDRLEN:HDRLEN + size]), False\n        except AssertionError as e:\n            raise IPCError(\n                \"error reading reply! (probably the socket was disconnected)\"\n            ) from e\n\n    @staticmethod\n    def pack(msg: Any, *, is_json: bool = False) -> bytes:\n        \"\"\"Pack the object into a message to pass\"\"\"\n        if is_json:\n            json_obj = json.dumps(msg)\n            return json_obj.encode()\n\n        msg_bytes = marshal.dumps(msg)\n        size = struct.pack(HDRFORMAT, len(msg_bytes))\n        return size + msg_bytes\n\n\nclass Client:\n    def __init__(self, fname: str, is_json=False) -> None:\n        \"\"\"Create a new IPC client\n\n        Parameters\n        ----------\n        fname : str\n            The file path to the file that is used to open the connection to\n            the running IPC server.\n        is_json : bool\n            Pack and unpack messages as json\n        \"\"\"\n        self.fname = fname\n        self.loop = asyncio.get_event_loop()\n        self.is_json = is_json\n\n    def call(self, data: Any) -> Any:\n        return self.send(data)\n\n    def send(self, msg: Any) -> Any:\n        \"\"\"Send the message and return the response from the server\n\n        If any exception is raised by the server, that will propogate out of\n        this call.\n        \"\"\"\n        return self.loop.run_until_complete(self.async_send(msg))\n\n    async def async_send(self, msg: Any) -> Any:\n        \"\"\"Send the message to the server\n\n        Connect to the server, then pack and send the message to the server,\n        then wait for and return the response from the server.\n        \"\"\"\n        try:\n            reader, writer = await asyncio.wait_for(\n                asyncio.open_unix_connection(path=self.fname), timeout=3\n            )\n        except (ConnectionRefusedError, FileNotFoundError):\n            raise IPCError(\"Could not open {}\".format(self.fname))\n\n        try:\n            send_data = _IPC.pack(msg, is_json=self.is_json)\n            writer.write(send_data)\n            writer.write_eof()\n\n            read_data = await asyncio.wait_for(reader.read(), timeout=10)\n        except asyncio.TimeoutError:\n            raise IPCError(\"Server not responding\")\n        finally:\n            # see the note in Server._server_callback()\n            writer.close()\n            await writer.wait_closed()\n\n        data, _ = _IPC.unpack(read_data, is_json=self.is_json)\n\n        return data\n\n\nclass Server:\n    def __init__(self, fname: str, handler) -> None:\n        self.fname = fname\n        self.handler = handler\n        self.server = None  # type: Optional[asyncio.AbstractServer]\n\n        if os.path.exists(fname):\n            os.unlink(fname)\n\n        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)\n        flags = fcntl.fcntl(self.sock.fileno(), fcntl.F_GETFD)\n        fcntl.fcntl(self.sock.fileno(), fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)\n        self.sock.bind(self.fname)\n\n    async def _server_callback(\n        self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter\n    ) -> None:\n        \"\"\"Callback when a connection is made to the server\n\n        Read the data sent from the client, execute the requested command, and\n        send the reply back to the client.\n        \"\"\"\n        try:\n            logger.debug(\"Connection made to server\")\n            data = await reader.read()\n            logger.debug(\"EOF received by server\")\n\n            req, is_json = _IPC.unpack(data)\n        except IPCError:\n            logger.warn(\"Invalid data received, closing connection\")\n        else:\n            if req[1] == \"restart\":\n                # if we are going to restart, close the connection first, as we won't be back\n                logger.debug(\"Closing connection on restart\")\n                writer.write_eof()\n\n            rep = self.handler(req)\n\n            result = _IPC.pack(rep, is_json=is_json)\n\n            logger.debug(\"Sending result on receive EOF\")\n            writer.write(result)\n            logger.debug(\"Closing connection on receive EOF\")\n            writer.write_eof()\n        finally:\n            writer.close()\n            await writer.wait_closed()\n\n    async def __aenter__(self) -> \"Server\":\n        \"\"\"Start and return the server\"\"\"\n        await self.start()\n        return self\n\n    async def __aexit__(self, exc_type, exc_value, tb) -> None:\n        \"\"\"Close and shutdown the server\"\"\"\n        await self.close()\n\n    async def start(self) -> None:\n        \"\"\"Start the server\"\"\"\n        assert self.server is None\n\n        logger.debug(\"Starting server\")\n        server_coroutine = asyncio.start_unix_server(\n            self._server_callback, sock=self.sock\n        )\n        self.server = await server_coroutine\n\n    async def close(self) -> None:\n        \"\"\"Close and shutdown the server\"\"\"\n        assert self.server is not None\n\n        logger.debug(\"Stopping server on close\")\n        self.server.close()\n        await self.server.wait_closed()\n\n        self.server = None\n", "path": "libqtile/ipc.py"}], "after_files": [{"content": "# Copyright (c) 2008, Aldo Cortesi. All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"\n    A simple IPC mechanism for communicating between two local processes. We\n    use marshal to serialize data - this means that both client and server must\n    run the same Python version, and that clients must be trusted (as\n    un-marshalling untrusted data can result in arbitrary code execution).\n\"\"\"\nimport asyncio\nimport fcntl\nimport json\nimport marshal\nimport os.path\nimport socket\nimport struct\nfrom typing import Any, Optional, Tuple\n\nfrom libqtile.log_utils import logger\nfrom libqtile.utils import get_cache_dir\n\nHDRFORMAT = \"!L\"\nHDRLEN = struct.calcsize(HDRFORMAT)\n\nSOCKBASE = \"qtilesocket.%s\"\n\n\ndef find_sockfile(display: str = None):\n    \"\"\"Finds the appropriate socket file for the given display\"\"\"\n    display = display or os.environ.get(\"DISPLAY\") or \":0.0\"\n    if \".\" not in display:\n        display += \".0\"\n    cache_directory = get_cache_dir()\n    return os.path.join(cache_directory, SOCKBASE % display)\n\n\nclass IPCError(Exception):\n    pass\n\n\nclass _IPC:\n    \"\"\"A helper class to handle properly packing and unpacking messages\"\"\"\n\n    @staticmethod\n    def unpack(data: bytes, *, is_json: Optional[bool] = None) -> Tuple[Any, bool]:\n        \"\"\"Unpack the incoming message\n\n        Parameters\n        ----------\n        data : bytes\n            The incoming message to unpack\n        is_json : Optional[bool]\n            If the message should be unpacked as json.  By default, try to\n            unpack json and fallback gracefully to marshalled bytes.\n\n        Returns\n        -------\n        Tuple[Any, bool]\n            A tuple of the unpacked object and a boolean denoting if the\n            message was deserialized using json.  If True, the return message\n            should be packed as json.\n        \"\"\"\n        if is_json is None or is_json:\n            try:\n                return json.loads(data.decode()), True\n            except ValueError as e:\n                if is_json:\n                    raise IPCError(\"Unable to decode json data\") from e\n\n        try:\n            assert len(data) >= HDRLEN\n            size = struct.unpack(HDRFORMAT, data[:HDRLEN])[0]\n            assert size >= len(data[HDRLEN:])\n            return marshal.loads(data[HDRLEN:HDRLEN + size]), False\n        except AssertionError as e:\n            raise IPCError(\n                \"error reading reply! (probably the socket was disconnected)\"\n            ) from e\n\n    @staticmethod\n    def pack(msg: Any, *, is_json: bool = False) -> bytes:\n        \"\"\"Pack the object into a message to pass\"\"\"\n        if is_json:\n            json_obj = json.dumps(msg)\n            return json_obj.encode()\n\n        msg_bytes = marshal.dumps(msg)\n        size = struct.pack(HDRFORMAT, len(msg_bytes))\n        return size + msg_bytes\n\n\nclass Client:\n    def __init__(self, fname: str, is_json=False) -> None:\n        \"\"\"Create a new IPC client\n\n        Parameters\n        ----------\n        fname : str\n            The file path to the file that is used to open the connection to\n            the running IPC server.\n        is_json : bool\n            Pack and unpack messages as json\n        \"\"\"\n        self.fname = fname\n        self.loop = asyncio.get_event_loop()\n        self.is_json = is_json\n\n    def call(self, data: Any) -> Any:\n        return self.send(data)\n\n    def send(self, msg: Any) -> Any:\n        \"\"\"Send the message and return the response from the server\n\n        If any exception is raised by the server, that will propogate out of\n        this call.\n        \"\"\"\n        return self.loop.run_until_complete(self.async_send(msg))\n\n    async def async_send(self, msg: Any) -> Any:\n        \"\"\"Send the message to the server\n\n        Connect to the server, then pack and send the message to the server,\n        then wait for and return the response from the server.\n        \"\"\"\n        try:\n            reader, writer = await asyncio.wait_for(\n                asyncio.open_unix_connection(path=self.fname), timeout=3\n            )\n        except (ConnectionRefusedError, FileNotFoundError):\n            raise IPCError(\"Could not open {}\".format(self.fname))\n\n        try:\n            send_data = _IPC.pack(msg, is_json=self.is_json)\n            writer.write(send_data)\n            writer.write_eof()\n\n            read_data = await asyncio.wait_for(reader.read(), timeout=10)\n        except asyncio.TimeoutError:\n            raise IPCError(\"Server not responding\")\n        finally:\n            # see the note in Server._server_callback()\n            writer.close()\n            await writer.wait_closed()\n\n        data, _ = _IPC.unpack(read_data, is_json=self.is_json)\n\n        return data\n\n\nclass Server:\n    def __init__(self, fname: str, handler) -> None:\n        self.fname = fname\n        self.handler = handler\n        self.server = None  # type: Optional[asyncio.AbstractServer]\n\n        if os.path.exists(fname):\n            os.unlink(fname)\n\n        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)\n        flags = fcntl.fcntl(self.sock.fileno(), fcntl.F_GETFD)\n        fcntl.fcntl(self.sock.fileno(), fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)\n        self.sock.bind(self.fname)\n\n    async def _server_callback(\n        self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter\n    ) -> None:\n        \"\"\"Callback when a connection is made to the server\n\n        Read the data sent from the client, execute the requested command, and\n        send the reply back to the client.\n        \"\"\"\n        try:\n            logger.debug(\"Connection made to server\")\n            data = await reader.read()\n            logger.debug(\"EOF received by server\")\n\n            req, is_json = _IPC.unpack(data)\n        except IPCError:\n            logger.warn(\"Invalid data received, closing connection\")\n        else:\n            rep = self.handler(req)\n\n            result = _IPC.pack(rep, is_json=is_json)\n\n            logger.debug(\"Sending result on receive EOF\")\n            writer.write(result)\n            logger.debug(\"Closing connection on receive EOF\")\n            writer.write_eof()\n        finally:\n            writer.close()\n            await writer.wait_closed()\n\n    async def __aenter__(self) -> \"Server\":\n        \"\"\"Start and return the server\"\"\"\n        await self.start()\n        return self\n\n    async def __aexit__(self, exc_type, exc_value, tb) -> None:\n        \"\"\"Close and shutdown the server\"\"\"\n        await self.close()\n\n    async def start(self) -> None:\n        \"\"\"Start the server\"\"\"\n        assert self.server is None\n\n        logger.debug(\"Starting server\")\n        server_coroutine = asyncio.start_unix_server(\n            self._server_callback, sock=self.sock\n        )\n        self.server = await server_coroutine\n\n    async def close(self) -> None:\n        \"\"\"Close and shutdown the server\"\"\"\n        assert self.server is not None\n\n        logger.debug(\"Stopping server on close\")\n        self.server.close()\n        await self.server.wait_closed()\n\n        self.server = None\n", "path": "libqtile/ipc.py"}]}