Skip to content

Commit 375feff

Browse files
committed
fix: make accept/proxy thread robust against exceptions during setup, preventing resource leaks
1 parent 0405614 commit 375feff

1 file changed

Lines changed: 18 additions & 4 deletions

File tree

‎google/cloud/sql/connector/psycopg.py‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -155,18 +155,32 @@ def connect(
155155

156156
def _accept_and_proxy() -> None:
157157
"""Accept one connection then proxy bytes until the connection closes."""
158+
unix_conn = None
158159
try:
159160
unix_conn, _ = local_sock.accept()
160161
local_sock.close()
161162
logger.debug("psycopg proxy: accepted connection, starting proxy")
162-
except OSError as e:
163-
logger.debug("psycopg proxy: accept failed: %s", e)
163+
_proxy(unix_conn, remote_sock)
164+
except Exception as e: # noqa: BLE001
165+
logger.debug("psycopg proxy: error in accept/proxy thread: %s", e)
166+
# Ensure cleanup on any exception
167+
if unix_conn:
168+
try:
169+
unix_conn.shutdown(socket.SHUT_RDWR)
170+
except OSError:
171+
pass
172+
try:
173+
unix_conn.close()
174+
except OSError:
175+
pass
176+
try:
177+
remote_sock.shutdown(socket.SHUT_RDWR)
178+
except OSError:
179+
pass
164180
try:
165181
remote_sock.close()
166182
except OSError:
167183
pass
168-
return
169-
_proxy(unix_conn, remote_sock)
170184

171185
threading.Thread(target=_accept_and_proxy, daemon=True).start()
172186

0 commit comments

Comments
 (0)