pgsql: Avoid resource leaks when a dblink connection fails.

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Avoid resource leaks when a dblink connection fails.
Date: 2025-05-29 14:40:21
Message-ID: E1uKeQe-000aax-0G@gemulon.postgresql.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Avoid resource leaks when a dblink connection fails.

If we hit out-of-memory between creating the PGconn and inserting
it into dblink's hashtable, we'd lose track of the PGconn, which
is quite bad since it represents a live connection to a remote DB.
Fix by rearranging things so that we create the hashtable entry
first.

Also reduce the number of states we have to deal with by getting rid
of the separately-allocated remoteConn object, instead allocating it
in-line in the hashtable entries. (That incidentally removes a
session-lifespan memory leak observed in the regression tests.)

There is an apparently-irreducible remaining OOM hazard, which
is that if the connection fails at the libpq level (ie it's
CONNECTION_BAD) then we have to pstrdup the PGconn's error message
before we can release it, and theoretically that could fail. However,
in such cases we're only leaking memory not a live remote connection,
so I'm not convinced that it's worth sweating over.

This is a pretty low-probability failure mode of course, but losing
a live connection seems bad enough to justify back-patching.

Author: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Reviewed-by: Matheus Alcantara <matheusssilv97(at)gmail(dot)com>
Discussion: https://postgr.es/m/1346940.1748381911@sss.pgh.pa.us
Backpatch-through: 13

Branch
------
REL_17_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/e20b3256ae468cb5979e861a1d6886baa4c4d42e

Modified Files
--------------
contrib/dblink/dblink.c | 78 ++++++++++++++++++++++++++-----------------------
1 file changed, 42 insertions(+), 36 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Bruce Momjian 2025-05-29 16:37:30 pgsql: doc PG 18 relnotes: modify async I/O item for other improvements
Previous Message Fujii Masao 2025-05-29 08:53:27 pgsql: Fix assertion failure in pg_prewarm() on objects without storage