pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
[Proposal] add portaddr like hostaddr
11+ messages / 3 participants
[nested] [flat]

* [Proposal] add portaddr like hostaddr
@ 2026-08-13 18:49 Diego <mrstephenamell@gmail.com>
  2026-08-24 19:23 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  0 siblings, 1 reply; 11+ messages in thread

From: Diego @ 2026-08-13 18:49 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org; +Cc: Christoph Berg <myon@debian.org>

Hi Hackers!

tl;dr: I want to add portaddr, like hostaddr, when the ssh tunnels uses 
dynamic ports is a mess.
        From my last attempt, [1], I undertand it sounds better in my 
mind that the first try ;p


Proposal
--------

Add a libpq connection parameter that says where the server is actually
reached, so that port can go on identifying it -- exactly what hostaddr
does for host.  The .pgpass lookup then stays on the logical (host, port)
pair, and the password file code does not change at all.

I do not have a strong opinion on the name: portaddr is the one that
mirrors hostaddr, but I am happy to take suggestions.

It is also easy to reason about for security: like hostaddr, it is an
explicit, opt-in assertion by the user, and nothing changes unless it is
given.

This is not hypothetical. I ran into it myself while adding SSH tunnel
support to pgcli (a widely used Postgres CLI): with the tunnel active, an
explicit-port .pgpass entry never matches, because the lookup happens
against the random local forwarding port. The user is prompted for a
password even though the matching entry is right there, and only a
wildcard port papers over it. Other tools hit the same wall:

- pgAdmin 4: control the SSH tunnel local port for .pgpass matching
https://github.com/pgadmin-org/pgadmin4/issues/6903

- DBeaver: .pgpass looked up by 127.0.0.1 through an SSH tunnel
https://github.com/dbeaver/dbeaver/issues/16499

- pgcli: SSH tunnel rewrites the port before the .pgpass lookup (myself)
https://github.com/dbcli/pgcli/pull/1546


Recap, since the approach changed
---------------------------------

The first version of this proposal added a parameter that affected only
the .pgpass lookup.  Christoph pointed out [2] that for a tunnel you open
by hand, with a fixed local port, you can simply write that port into
.pgpass.  That is correct, and I withdrew that part of the motivation.

What remains is the case where the local port is not known when the
password file is written, because the tunnel is not opened by hand.
Clients that open it for you bind the local end to port 0 and let the
kernel choose.  pgcli, the case I ran into, does exactly that: it hands
sshtunnel a local bind address with no port in it,

     "local_bind_address": ("127.0.0.1",),

and only afterwards asks which port it got,

     port = self.ssh_tunnel.local_bind_ports[0]

which it then substitutes into the connection string.  The forwarding
port is different on every run, and those two lines are precisely what
breaks the .pgpass lookup.  pgAdmin 4 and DBeaver open their own tunnels
the same way, which is what the two reports above are about, and outside
SSH the same shape shows up in kubectl port-forward, where ":5432" means
"listen on a random local port".

There is no port you can write into .pgpass in advance.

(Plain ssh(1) cannot even express this: OpenSSH rejects port 0 on -L and
accepts it only for -R, so the wrappers pick a free local port
themselves and pass it to -L.  Same outcome for .pgpass.)

The model
---------

libpq already allows the host that identifies a server to differ from the
address it is reached at:

     host identifies the server, hostaddr is where we connect,
     and the password file is searched by host.

v2 does the same for ports, instead of adding a password-file-only knob:

     port identifies the server, portaddr is where we connect,
     and the password file is searched by port.

The tunnel case is then spelled

     host=db.example.com hostaddr=127.0.0.1 port=5432 portaddr=39907

and the password file entry is the one a direct connection already uses:

     db.example.com:5432:appdb:alice:secret

What I like about this shape is that the password file code does not
change at all.  passwordFromFile() already receives connhost[i].port, so
keeping portaddr in a separate field leaves the lookup logical by
construction.  That is the same reasoning as e3f99e03e2e, which settled
that the .pgpass host key is host and not hostaddr.

The patches
-----------

Both patches are attached.  They apply cleanly on master as of
957d4eae52e.

0001  libpq: add portaddr, the port equivalent of hostaddr
       The parameter, the PGPORTADDR environment variable, documentation,
       and a TAP test.  It also contains a psql \connect fix, see below.

0002  libpq: add PQportaddr(), and show the port address in psql \conninfo
       The accessor mirroring PQhostaddr(), and the psql display. This one
       is separable: if the list does not want it, 0001 stands on its own.

The new test, src/interfaces/libpq/t/007_portaddr.pl, needs the server to
listen on TCP, so it is skipped unless PG_TEST_EXTRA lists portaddr:

     make check-world PG_TEST_EXTRA=portaddr

The environment variable works for meson builds as well.  Without it the
test plans skip_all and nothing else in the suite is affected.

Decisions I made, and where I would like guidance
-------------------------------------------------

* portaddr applies to TCP only, and is ignored for Unix-domain socket
   connections, whose socket file name is built from port. hostaddr does
   not apply to those either.

* The list semantics follow port rather than hostaddr: a single portaddr
   applies to every host, otherwise the element count must match the host
   count, and an empty item means "use the corresponding port". hostaddr
   has to match exactly because it determines the number of hosts;
   portaddr does not.

* port is still parsed and range-checked even when portaddr overrides it.
   hostaddr does not validate host, but any string is a plausible host
   name, whereas a port has a syntax; silently accepting a bad value that
   then becomes the password file search key seemed worse than erroring
   out.

* PQport() keeps returning port, mirroring PQhost(), which returns host
   and not hostaddr.  Its documentation promised "the port actually
   connected to", so I reworded it, and 0002 adds PQportaddr() for the
   actual port.

* Connection failure messages report the port actually attempted, since
   "connection to server at ..., port N failed" is about where we tried to
   go.

* psql's \connect drops an inherited hostaddr when the host argument
   changes.  portaddr needs the same treatment, and it has to key on both:
   a portaddr describes where to reach one particular server, so 0001 drops
   it when either the host or the port argument changes.  Without that,
   "\c - - otherhost" would keep tunnelling to the old portaddr on a
   different machine.  This is in 0001 because leaving it out is a bug, not
   a missing polish item.

* PGPORTADDR is added to the environment variables cleared by pg_regress
   and PostgreSQL::Test::Utils, next to PGHOSTADDR, which is scrubbed there
   for exactly the same reason: it would silently redirect test connections
   away from the temporary cluster.

* The new TAP test has to make the server listen on TCP, since portaddr
   does not apply to Unix-domain sockets.  Following ssl, kerberos, ldap and
   load_balance, it runs only when PG_TEST_EXTRA lists portaddr, and
   regress.sgml documents the new value.  I am not attached to the name, or
   to having a keyword of its own rather than folding it into an existing
   one.

The POC #1 first flight
-----------------------

daf@t:postgres$ test=/home/daf/scripts/postgres/portaddr-demo
daf@t:postgres$ BIN_CON="$test/con-el-patch/usr/local/bin"
daf@t:postgres$ LIB_CON="$test/con-el-patch/usr/local/lib/x86_64-linux-gnu"
daf@t:postgres$ PSQL_CON="$test/con-el-patch/usr/local/bin/psql"
daf@t:postgres$ LIB_SIN="$test/sin-patch/usr/local/lib/x86_64-linux-gnu"
daf@t:postgres$ PSQL_SIN="$test/sin-patch/usr/local/bin/psql"
daf@t:postgres$ unset PGPASSWORD PGPORTADDR
daf@t:postgres$ export LD_LIBRARY_PATH="$LIB_CON"
daf@t:postgres$ export PGDATA=/tmp/pgd-test-portaddr
daf@t:postgres$ export PGPASSFILE=/tmp/pgpass-test-portaddr
daf@t:postgres$
daf@t:postgres$ # init
daf@t:postgres$
daf@t:postgres$ "$BIN_CON/initdb" -D "$PGDATA" -U postgres -A trust 
--no-sync
The files belonging to this database system will be owned by user "daf".
This user must also own the server process.

The database cluster will be initialized with locale "C.UTF-8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are enabled.

creating directory /tmp/pgd-test-portaddr ... ok
creating subdirectories ... ok
selecting dynamic shared memory implementation ... posix
selecting default "max_connections" ... 100
selecting default "shared_buffers" ... 128MB
selecting default time zone ... America/Argentina/Buenos_Aires
creating configuration files ... ok
running bootstrap script ... ok
performing post-bootstrap initialization ... ok

Sync to disk skipped.
The data directory might become corrupt if the operating system crashes.

Success. You can now start the database server using:

/home/daf/scripts/postgres/portaddr-demo/con-el-patch/usr/local/bin/pg_ctl 
-D /tmp/pgd-test-portaddr -l logfile start

daf@t:postgres$ printf 'local all all trust\nhost all all 127.0.0.1/32 
scram-sha-256\n' > "$PGDATA/pg_hba.conf"
daf@t:postgres$ cat "$PGDATA/pg_hba.conf"
local all all trust
host all all 127.0.0.1/32 scram-sha-256
daf@t:postgres$ "$BIN_CON/pg_ctl" -D "$PGDATA" -o "-p 5441 -c 
listen_addresses=127.0.0.1" -w start
waiting for server to start....2026-08-13 14:23:31.316 -03 [1018117] 
LOG:  starting PostgreSQL 20devel on x86_64-linux, compiled by 
gcc-12.2.0, 64-bit
2026-08-13 14:23:31.316 -03 [1018117] LOG:  listening on IPv4 address 
"127.0.0.1", port 5441
2026-08-13 14:23:31.319 -03 [1018117] LOG:  listening on Unix socket 
"/tmp/.s.PGSQL.5441"
2026-08-13 14:23:31.325 -03 [1018122] LOG:  database system was shut 
down at 2026-08-13 14:22:49 -03
2026-08-13 14:23:31.330 -03 [1018117] LOG:  database system is ready to 
accept connections
  done
server started
daf@t:postgres$ "$BIN_CON/psql" -X -p 5441 -U postgres -h /tmp -d 
postgres -c "create role tuser login password 'sekret';"
CREATE ROLE
daf@t:postgres$
daf@t:postgres$ echo "127.0.0.1:5440:postgres:tuser:sekret" > "$PGPASSFILE"
daf@t:postgres$ chmod 600 "$PGPASSFILE"
daf@t:postgres$

daf@t:postgres$
daf@t:postgres$ cat "$PGPASSFILE"
127.0.0.1:5440:postgres:tuser:sekret
daf@t:postgres$
daf@t:postgres$ # 1) Original without patch, FAIL -> bug: .pgpass not match
LD_LIBRARY_PATH="$LIB_SIN" "$PSQL_SIN" -X -w "host=127.0.0.1 port=5441 
user=tuser dbname=postgres" -tAc "select 'AUTENTICO-OK'"
psql: error: connection to server at "127.0.0.1", port 5441 failed: 
fe_sendauth: no password supplied
daf@t:postgres$
daf@t:postgres$ # 2) without patch + portaddr -> FAIL
LD_LIBRARY_PATH="$LIB_SIN" "$PSQL_SIN" -X -w "host=127.0.0.1 port=5440 
portaddr=5441 user=tuser dbname=postgres" -tAc "select 'AUTENTICO-OK'"
psql: error: invalid connection option "portaddr"
daf@t:postgres$
daf@t:postgres$ # 3) WITH patch + portaddr -> AUTENTICA (same line as 
#2, different libpq)
LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 port=5440 
portaddr=5441 user=tuser dbname=postgres" -tAc "select 'AUTENTICO-OK'"
AUTENTICO-OK
daf@t:postgres$
daf@t:postgres$ # 4) WITH patch, no portaddr -> FAIL, default not changed
LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 port=5441 
user=tuser dbname=postgres" -tAc "select 'AUTENTICO-OK'"
psql: error: connection to server at "127.0.0.1", port 5441 failed: 
fe_sendauth: no password supplied
daf@t:postgres$
daf@t:postgres$ # 5) WITH patch, env var instead of the parameter -> 
AUTENTICA
PGPORTADDR=5441 LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w 
"host=127.0.0.1 port=5440 user=tuser dbname=postgres" -tAc "select 
'AUTENTICO-OK'"
AUTENTICO-OK
daf@t:postgres$ # 6) WITH patch, what the client sees -> Server Port 
5440 / Port Address 5441
LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 port=5440 
portaddr=5441 user=tuser dbname=postgres" -c "\conninfo"
       Connection Information
       Parameter       |   Value
----------------------+-----------
  Database             | postgres
  Client User          | tuser
  Host                 | 127.0.0.1
  Server Port          | 5440
  Port Address         | 5441
  Options              |
  Protocol Version     | 3.2
  Password Used        | true
  GSSAPI Authenticated | false
  Backend PID          | 1018919
  SSL Connection       | false
  Superuser            | off
  Hot Standby          | off
(13 rows)

daf@t:postgres$
daf@t:postgres$ 2026-08-13 14:28:31.428 -03 [1018120] LOG: checkpoint 
starting: time
2026-08-13 14:28:36.176 -03 [1018120] LOG:  checkpoint complete: time: 
wrote 47 buffers (0.3%), wrote 3 SLRU buffers; 0 WAL file(s) added, 0 
removed, 0 recycled; write=4.713 s, sync=0.024 s, total=4.748 s; sync 
files=15, longest=0.018 s, average=0.002 s; distance=345 kB, 
estimate=345 kB; lsn=0/017D4910, redo lsn=0/017D4878

"$BIN_CON/pg_ctl" -D "$PGDATA" -m immediate stop
waiting for server to shut down....2026-08-13 14:29:17.551 -03 [1018117] 
LOG:  received immediate shutdown request
2026-08-13 14:29:17.563 -03 [1018117] LOG:  database system is shut down
  done
server stopped

The POC #2 withreal case
------------------------


daf@t:postgres$ # ---- setup
daf@t:postgres$ test=/home/daf/scripts/postgres/portaddr-demo
daf@t:postgres$ LIB_CON="$test/con-el-patch/usr/local/lib/x86_64-linux-gnu"
daf@t:postgres$ PSQL_CON="$test/con-el-patch/usr/local/bin/psql"
daf@t:postgres$ LIB_SIN="$test/sin-patch/usr/local/lib/x86_64-linux-gnu"
daf@t:postgres$ PSQL_SIN="$test/sin-patch/usr/local/bin/psql"
daf@t:postgres$ SSH_HOST=beta
daf@t:postgres$ REAL_HOST=beta.xxxx.yyyy.zzz
daf@t:postgres$ REAL_PORT=55432
daf@t:postgres$ LOCAL_PORT=5533
daf@t:postgres$ SSH_SOCK=/tmp/portaddr-beta-ssh.sock
daf@t:postgres$
daf@t:postgres$ unset PGPASSWORD PGPORTADDR
daf@t:postgres$ export PGPASSFILE=/tmp/pgpass-demo-portaddr-beta
daf@t:postgres$
daf@t:postgres$ ssh -M -S "$SSH_SOCK" -f -N "$SSH_HOST"
daf@t:postgres$ ssh -S "$SSH_SOCK" -O forward -L 
$LOCAL_PORT:localhost:$REAL_PORT "$SSH_HOST"
daf@t:postgres$ ss -ltn | grep $LOCAL_PORT
LISTEN 0      128        127.0.0.1:5533       0.0.0.0:*
daf@t:postgres$
daf@t:postgres$ cat "$PGPASSFILE"
127.0.0.1:55432:*:daf:sekret
daf@t:postgres$ chmod 600 "$PGPASSFILE"
daf@t:postgres$
daf@t:postgres$
daf@t:postgres$ # 1) Original without patch, FAIL -> bug: .pgpass no 
matchea el puerto del tunel
LD_LIBRARY_PATH="$LIB_SIN" "$PSQL_SIN" -X -w "host=127.0.0.1 
port=$LOCAL_PORT user=daf dbname=daf" -tAc "select 'AUTENTICO-OK'"
psql: error: connection to server at "127.0.0.1", port 5533 failed: 
fe_sendauth: no password supplied
daf@t:postgres$
daf@t:postgres$ # 2) without patch + portaddr -> FAIL
LD_LIBRARY_PATH="$LIB_SIN" "$PSQL_SIN" -X -w "host=127.0.0.1 
port=$REAL_PORT portaddr=$LOCAL_PORT user=daf dbname=daf" -tAc "select 
'AUTENTICO-OK'"
psql: error: invalid connection option "portaddr"
daf@t:postgres$
daf@t:postgres$ # 3) WITH patch + portaddr -> AUTENTICA (same like #2, 
other libpq)
LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 
port=$REAL_PORT portaddr=$LOCAL_PORT user=daf dbname=daf" -tAc "select 
'AUTENTICO-OK'"
AUTENTICO-OK
daf@t:postgres$ # 4) WITH patch, no portaddr -> FAIL, same default
LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 
port=$LOCAL_PORT user=daf dbname=daf" -tAc "select 'AUTENTICO-OK'"
psql: error: connection to server at "127.0.0.1", port 5533 failed: 
fe_sendauth: no password supplied
daf@t:postgres$
daf@t:postgres$ # 5) WITH patch, env var en vez del parametro -> AUTENTICA
PGPORTADDR=$LOCAL_PORT LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w 
"host=127.0.0.1 port=$REAL_PORT user=daf dbname=daf" -tAc "select 
'AUTENTICO-OK'"
AUTENTICO-OK
daf@t:postgres$
daf@t:postgres$ # 6) WITH patch, lo que ve el cliente -> Server Port 
55432 / Port Address 5533 / Password Used true
LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 
port=$REAL_PORT portaddr=$LOCAL_PORT user=daf dbname=daf" -c "\conninfo"
       Connection Information
       Parameter       |   Value
----------------------+-----------
  Database             | daf
  Client User          | daf
  Host                 | 127.0.0.1
  Server Port          | 55432
  Port Address         | 5533
  Options              |
  Protocol Version     | 3.0
  Password Used        | true
  GSSAPI Authenticated | false
  Backend PID          | 290199
  SSL Connection       | false
  Superuser            | on
  Hot Standby          | off
(13 rows)

daf@t:postgres$
daf@t:postgres$
# ---------------------------------------------------------------
# 7) THE MAIN CASE: the full symmetry, using your REAL ~/.pgpass untouched
#
#   host     = beta.xxxx.yyyy.zzz   hostaddr = 127.0.0.1
#   port     = 55432                      portaddr = 5533
#
# The LOGICAL pair (host, port) is how you know the server, and what the 
.pgpass
# lookup uses; the PHYSICAL pair (hostaddr, portaddr) is where the 
socket really
# goes. Without portaddr, hostaddr alone is not enough: you can lie 
about the
# host, but the port still gives you away.

daf@t:postgres$ unset PGPASSFILE
daf@t:postgres$
daf@t:postgres$ # without patch: hostaddr has been there for years, but 
the lookup still uses the tunnel port -> FAILS
LD_LIBRARY_PATH="$LIB_SIN" "$PSQL_SIN" -X -w "host=$REAL_HOST 
hostaddr=127.0.0.1 port=$LOCAL_PORT user=daf dbname=daf" -tAc "select 
'AUTENTICO-OK'"
psql: error: connection to server at "127.0.0.1", port 5533 failed: 
fe_sendauth: no password supplied
daf@t:postgres$
daf@t:postgres$ # WITH patch: (host,port) for the lookup + 
(hostaddr,portaddr) for the socket -> AUTHENTICATES
LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=$REAL_HOST 
hostaddr=127.0.0.1 port=$REAL_PORT portaddr=$LOCAL_PORT user=daf 
dbname=daf" -tAc "select 'AUTENTICO-OK'"
AUTENTICO-OK
daf@t:postgres$
daf@t:postgres$ # \conninfo shows the 4 rows together: Host / Host 
Address / Server Port / Port Address
LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=$REAL_HOST 
hostaddr=127.0.0.1 port=$REAL_PORT portaddr=$LOCAL_PORT user=daf 
dbname=daf" -c "\conninfo"
              Connection Information
       Parameter       |          Value
----------------------+--------------------------
  Database             | daf
  Client User          | daf
  Host                 | beta.xxxx.yyyy.zzz
  Host Address         | 127.0.0.1
  Server Port          | 55432
  Port Address         | 5533
  Options              |
  Protocol Version     | 3.0
  Password Used        | true
  GSSAPI Authenticated | false
  Backend PID          | 290265
  SSL Connection       | false
  Superuser            | on
  Hot Standby          | off
(14 rows)


And that's all folks.
Please, feel free to send feedback.


[1] 
https://www.postgresql.org/message-id/flat/001a6f1d-4adb-42b2-8bf6-44154ed0ab97%40gmail.com
[2] https://postgr.es/m/ak6FwxXWcBTvvpPo@msg.df7cb.de



Thank you all,
BR,
Diego

Attachments: download all (2 files, .tar.gz)

0002-libpq-add-PQportaddr-and-show-the-port-address-in-ps.patch (text/x-patch, 10.3K) download From 95b18284b16a196fb51505efaedac0d4eba980df Mon Sep 17 00:00:00 2001 From: Diego <mrstephenamell@gmail.com> Date: Mon, 27 Jul 2026 14:06:48 -0300 Subject: [PATCH v2 2/2] libpq: add PQportaddr(), and show the port address in psql \conninfo portaddr allows the port a connection is made to to differ from the port that identifies the server, but there was no way to ask libpq which port it actually used. Add PQportaddr(), which reports the port of the current connection just as PQhostaddr() reports its IP address; like that function, it reports nothing for Unix-domain socket connections, which have no port. Use it in psql's \conninfo, which grows a "Port Address" row displayed only when the port connected to differs from the port identifying the server -- the same rule the existing "Host Address" row follows. Discussion: https://postgr.es/m/001a6f1d-4adb-42b2-8bf6-44154ed0ab97@gmail.com --- doc/src/sgml/libpq.sgml | 24 ++++++++++++ src/bin/psql/command.c | 18 ++++++++- src/interfaces/libpq/exports.txt | 1 + src/interfaces/libpq/fe-connect.c | 52 +++++++++++++++++++++++++- src/interfaces/libpq/libpq-fe.h | 1 + src/interfaces/libpq/libpq-int.h | 1 + src/interfaces/libpq/t/007_portaddr.pl | 26 +++++++++++++ 7 files changed, 120 insertions(+), 3 deletions(-) diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index c2b078bd6a9..3f94d39bd33 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -2860,6 +2860,30 @@ char *PQport(const PGconn *conn); </listitem> </varlistentry> + <varlistentry id="libpq-PQportaddr"> + <term><function>PQportaddr</function><indexterm><primary>PQportaddr</primary></indexterm></term> + + <listitem> + <para> + Returns the port that the active connection was actually made to. + This can be the port given by the <literal>port</literal> parameter, + or a port provided through the <literal>portaddr</literal> parameter. +<synopsis> +char *PQportaddr(const PGconn *conn); +</synopsis> + </para> + + <para> + <xref linkend="libpq-PQportaddr"/> returns <symbol>NULL</symbol> if the + <parameter>conn</parameter> argument is <symbol>NULL</symbol>. + Otherwise, if there is an error producing the port information (perhaps + if the connection has not been fully established or there was an + error), or if the connection is made over a Unix-domain socket, it + returns an empty string. + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-PQtty"> <term><function>PQtty</function><indexterm><primary>PQtty</primary></indexterm></term> diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c index 7f4090e0d8d..af428dbf2f0 100644 --- a/src/bin/psql/command.c +++ b/src/bin/psql/command.c @@ -794,6 +794,9 @@ exec_command_conninfo(PsqlScanState scan_state, bool active_branch) char *host; bool print_hostaddr; char *hostaddr; + bool print_portaddr; + char *port, + *portaddr; char *protocol_version, *backend_pid; int ssl_in_use, @@ -815,6 +818,8 @@ exec_command_conninfo(PsqlScanState scan_state, bool active_branch) /* Get values for the parameters */ host = PQhost(pset.db); hostaddr = PQhostaddr(pset.db); + port = PQport(pset.db); + portaddr = PQportaddr(pset.db); version_num = PQfullProtocolVersion(pset.db); protocol_version = psprintf("%d.%d", version_num / 10000, version_num % 10000); @@ -827,6 +832,10 @@ exec_command_conninfo(PsqlScanState scan_state, bool active_branch) print_hostaddr = (!is_unixsock_path(host) && hostaddr && *hostaddr && strcmp(host, hostaddr) != 0); + /* Likewise for the port actually connected to */ + print_portaddr = (!is_unixsock_path(host) && + portaddr && *portaddr && strcmp(port, portaddr) != 0); + /* Determine the exact number of rows to print */ rows = 12; cols = 2; @@ -834,6 +843,8 @@ exec_command_conninfo(PsqlScanState scan_state, bool active_branch) rows += 6; if (print_hostaddr) rows++; + if (print_portaddr) + rows++; /* Set it all up */ printTableInit(&cont, &pset.popt.topt, _("Connection Information"), cols, rows); @@ -876,7 +887,12 @@ exec_command_conninfo(PsqlScanState scan_state, bool active_branch) /* Server Port */ printTableAddCell(&cont, _("Server Port"), false, false); - printTableAddCell(&cont, PQport(pset.db), false, false); + printTableAddCell(&cont, port, false, false); + if (print_portaddr) + { + printTableAddCell(&cont, _("Port Address"), false, false); + printTableAddCell(&cont, portaddr, false, false); + } /* Options */ printTableAddCell(&cont, _("Options"), false, false); diff --git a/src/interfaces/libpq/exports.txt b/src/interfaces/libpq/exports.txt index 1e3d5bd5867..2ac1198bc00 100644 --- a/src/interfaces/libpq/exports.txt +++ b/src/interfaces/libpq/exports.txt @@ -211,3 +211,4 @@ PQdefaultAuthDataHook 208 PQfullProtocolVersion 209 appendPQExpBufferVA 210 PQgetThreadLock 211 +PQportaddr 212 diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 69c38c6a367..5546073b770 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -2464,6 +2464,30 @@ getHostaddr(PGconn *conn, char *host_addr, int host_addr_len) host_addr[0] = '\0'; } +/* ---------- + * getPortaddr - + * Form the port number of the current connection, in the same way that + * getHostaddr() forms its IP address. conn->raddr must be valid. Nothing + * is reported for Unix-domain sockets, which have no port number. + * ---------- + */ +static void +getPortaddr(PGconn *conn, char *port_str, int port_str_len) +{ + struct sockaddr_storage *addr = &conn->raddr.addr; + + if (addr->ss_family == AF_INET || addr->ss_family == AF_INET6) + { + if (pg_getnameinfo_all(addr, conn->raddr.salen, + NULL, 0, + port_str, port_str_len, + NI_NUMERICSERV) != 0) + port_str[0] = '\0'; + } + else + port_str[0] = '\0'; +} + /* * emitHostIdentityInfo - * Speculatively append "connection to server so-and-so failed: " to @@ -3323,6 +3347,7 @@ keep_going: /* We will come back to here until there is */ { char host_addr[NI_MAXHOST]; + char port_str[NI_MAXSERV]; int sock_type; AddrInfo *addr_cur; @@ -3378,8 +3403,8 @@ keep_going: /* We will come back to here until there is goto error_return; /* - * Set connip, too. Note we purposely ignore strdup - * failure; not a big problem if it fails. + * Set connip and connport, too. Note we purposely ignore + * strdup failure; not a big problem if it fails. */ if (conn->connip != NULL) { @@ -3390,6 +3415,15 @@ keep_going: /* We will come back to here until there is if (host_addr[0]) conn->connip = strdup(host_addr); + if (conn->connport != NULL) + { + free(conn->connport); + conn->connport = NULL; + } + getPortaddr(conn, port_str, NI_MAXSERV); + if (port_str[0]) + conn->connport = strdup(port_str); + /* Try to create the socket */ sock_type = SOCK_STREAM; #ifdef SOCK_CLOEXEC @@ -5244,6 +5278,7 @@ freePGconn(PGconn *conn) free(conn->events); pqReleaseConnHosts(conn); free(conn->connip); + free(conn->connport); release_conn_addrinfo(conn); free(conn->scram_client_key_binary); free(conn->scram_server_key_binary); @@ -7744,6 +7779,19 @@ PQport(const PGconn *conn) return DEF_PGPORT_STR; } +char * +PQportaddr(const PGconn *conn) +{ + if (!conn) + return NULL; + + /* Return the port actually connected to */ + if (conn->connhost != NULL && conn->connport != NULL) + return conn->connport; + + return ""; +} + /* * No longer does anything, but the function remains for API backwards * compatibility. diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 8ecb9b4a4c7..820fc9aa842 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -415,6 +415,7 @@ extern char *PQpass(const PGconn *conn); extern char *PQhost(const PGconn *conn); extern char *PQhostaddr(const PGconn *conn); extern char *PQport(const PGconn *conn); +extern char *PQportaddr(const PGconn *conn); extern char *PQtty(const PGconn *conn); extern char *PQoptions(const PGconn *conn); extern ConnStatusType PQstatus(const PGconn *conn); diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 3ccb063d453..d18c9ce18b8 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -490,6 +490,7 @@ struct pg_conn int whichhost; /* host we're currently trying/connected to */ pg_conn_host *connhost; /* details about each named host */ char *connip; /* IP address for current network connection */ + char *connport; /* port number for current network connection */ /* * The pending command queue as a singly-linked list. Head is the command diff --git a/src/interfaces/libpq/t/007_portaddr.pl b/src/interfaces/libpq/t/007_portaddr.pl index 5ecb573d8a7..856101c9541 100644 --- a/src/interfaces/libpq/t/007_portaddr.pl +++ b/src/interfaces/libpq/t/007_portaddr.pl @@ -48,6 +48,32 @@ $node->connect_ok( sql => "\\echo :PORT", expected_stdout => qr/^$unusedport$/); +# PQportaddr() reports the port actually connected to, and psql shows it in +# \conninfo when it differs from the port identifying the server. +my ($ret, $stdout, $stderr) = $node->psql( + 'postgres', + "\\conninfo", + extra_params => ['-w'], + connstr => "host=127.0.0.1 port=$unusedport portaddr=$realport", + on_error_stop => 0); +is($ret, 0, "\\conninfo with portaddr succeeds"); +like($stdout, qr/^Server Port\|$unusedport$/m, + "\\conninfo reports port as the server port"); +like($stdout, qr/^Port Address\|$realport$/m, + "\\conninfo reports portaddr as the port address"); + +($ret, $stdout, $stderr) = $node->psql( + 'postgres', + "\\conninfo", + extra_params => ['-w'], + connstr => "host=127.0.0.1 port=$realport", + on_error_stop => 0); +is($ret, 0, "\\conninfo without portaddr succeeds"); +like($stdout, qr/^Server Port\|$realport$/m, + "\\conninfo without portaddr reports the port"); +unlike($stdout, qr/Port Address/, + "\\conninfo omits the port address when it matches port"); + # An empty portaddr means "connect to port", the historical behavior. $node->connect_ok( "host=127.0.0.1 port=$realport portaddr=", -- 2.43.0
0001-libpq-add-portaddr-the-port-equivalent-of-hostaddr.patch (text/x-patch, 29.1K) download From 3882d5952ca1c383b8408530f8a5351562ab1eba Mon Sep 17 00:00:00 2001 From: Diego <mrstephenamell@gmail.com> Date: Mon, 27 Jul 2026 14:06:35 -0300 Subject: [PATCH v2 1/2] libpq: add portaddr, the port equivalent of hostaddr libpq has long allowed the host name that identifies a server to differ from the address actually connected to: host names the server, hostaddr gives the address to reach it at, and the password file is searched using host. Ports have no such separation. The port parameter is both the port connected to and the port used as the password file search key, so a connection made through an intermediary listening on a different port -- an SSH tunnel, a connection proxy -- cannot use a password file entry written for the server itself. Writing the intermediary's port into the password file works when that port is fixed and known ahead of time, but not when it is assigned at connection time, as with "ssh -L 127.0.0.1:0:...", cloud database proxies, and GUI clients that manage their own tunnels. There the local port is unknown when the password file is written, and differs between sessions. Add a portaddr parameter, and a PGPORTADDR environment variable, that completes the model: when portaddr is given it is the port connected to, and port only identifies the server, exactly as host does when hostaddr is given. The password file lookup therefore keeps using port. Like hostaddr, portaddr applies only to TCP connections; it is ignored for Unix-domain sockets, whose socket file name is determined by port. psql's \connect drops a hostaddr inherited from the previous connection when the host argument changes. Do the same for portaddr when either the host or the port argument changes, so that reconnecting elsewhere is not silently redirected through the old address. PGPORTADDR is added to the environment variables cleared by pg_regress and PostgreSQL::Test::Utils, since like PGHOSTADDR it would otherwise redirect test connections away from the temporary cluster. The new TAP test opens a TCP listen socket, so it runs only when portaddr is listed in PG_TEST_EXTRA. Behavior is unchanged when portaddr is not specified. Discussion: https://postgr.es/m/001a6f1d-4adb-42b2-8bf6-44154ed0ab97@gmail.com --- doc/src/sgml/libpq.sgml | 97 ++++++++++++++- doc/src/sgml/ref/psql-ref.sgml | 8 +- doc/src/sgml/regress.sgml | 11 ++ src/bin/psql/command.c | 24 +++- src/interfaces/libpq/fe-cancel.c | 6 + src/interfaces/libpq/fe-connect.c | 76 ++++++++++- src/interfaces/libpq/libpq-int.h | 6 + src/interfaces/libpq/meson.build | 1 + src/interfaces/libpq/t/001_uri.pl | 6 + src/interfaces/libpq/t/007_portaddr.pl | 166 +++++++++++++++++++++++++ src/test/perl/PostgreSQL/Test/Utils.pm | 1 + src/test/regress/pg_regress.c | 2 + 12 files changed, 391 insertions(+), 13 deletions(-) create mode 100644 src/interfaces/libpq/t/007_portaddr.pl diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 7d3c3bb66d8..c2b078bd6a9 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -1085,12 +1085,14 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <para> It is possible to specify multiple hosts to connect to, so that they are tried in the given order. In the Keyword/Value format, the <literal>host</literal>, - <literal>hostaddr</literal>, and <literal>port</literal> options accept comma-separated + <literal>hostaddr</literal>, <literal>port</literal>, and + <literal>portaddr</literal> options accept comma-separated lists of values. The same number of elements must be given in each option that is specified, such that e.g., the first <literal>hostaddr</literal> corresponds to the first host name, the second <literal>hostaddr</literal> corresponds to the second host name, and so - forth. As an exception, if only one <literal>port</literal> is specified, it + forth. As an exception, if only one <literal>port</literal> + or <literal>portaddr</literal> is specified, it applies to all the hosts. </para> @@ -1251,6 +1253,73 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </listitem> </varlistentry> + <varlistentry id="libpq-connect-portaddr" xreflabel="portaddr"> + <term><literal>portaddr</literal></term> + <listitem> + <para> + Port number to actually connect to at the server host. When a nonempty + string is specified for this parameter, it determines where the + connection is made, and <xref linkend="libpq-connect-port"/> only + identifies the server &mdash; much as + <xref linkend="libpq-connect-host"/> still identifies the server when + <xref linkend="libpq-connect-hostaddr"/> is given. If this parameter + is not specified, the value of <literal>port</literal> is connected to, + which is the historical behavior. This parameter is ignored for + Unix-domain socket connections, whose socket file name is always + determined by <literal>port</literal>. + </para> + + <para> + Using <literal>portaddr</literal> allows the connection to be made + through an intermediary listening on a different port, such as an + <acronym>SSH</acronym> tunnel or a connection proxy, while the other + connection parameters continue to describe the server itself. In + particular, the port used to identify the connection in a password file + (see <xref linkend="libpq-pgpass"/>) is <literal>port</literal>, not + <literal>portaddr</literal>, so a password file entry written for the + server's own port keeps matching even when the intermediary listens on + a port that is not known in advance. The following rules are used: + <itemizedlist> + <listitem> + <para> + If <literal>port</literal> is specified + without <literal>portaddr</literal>, the connection is made to + <literal>port</literal>, which also identifies the connection. + </para> + </listitem> + <listitem> + <para> + If <literal>portaddr</literal> is specified + without <literal>port</literal>, the value + for <literal>portaddr</literal> gives the port to connect to, and + the default port number identifies the connection. + </para> + </listitem> + <listitem> + <para> + If both <literal>port</literal> and <literal>portaddr</literal> are + specified, the value for <literal>portaddr</literal> gives the port + to connect to. The value for <literal>port</literal> is used only + to identify the connection. + </para> + </listitem> + </itemizedlist> + Note that authentication is likely to fail if <literal>port</literal> + is not the port of the server reached + at <literal>portaddr</literal>, since the password file entry that is + selected will then be the wrong one. + </para> + + <para> + A comma-separated list of <literal>portaddr</literal> values is also + accepted, in which case it must have the same length as the host list, + or it may specify a single value to be used for all hosts. An empty + item in the list causes the corresponding <literal>port</literal> value + to be used. See <xref linkend="libpq-multiple-hosts"/> for details. + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-dbname" xreflabel="dbname"> <term><literal>dbname</literal></term> <listitem> @@ -2766,8 +2835,12 @@ char *PQport(const PGconn *conn); </para> <para> - If multiple ports were specified in the connection parameters, - <xref linkend="libpq-PQport"/> returns the port actually connected to. + If the connection parameters specified both <literal>port</literal> and + <literal>portaddr</literal>, then <xref linkend="libpq-PQport"/> will + return the <literal>port</literal> information. If multiple ports were + specified in the connection parameters, + <xref linkend="libpq-PQport"/> returns the port of the host actually + connected to. </para> <para> @@ -9107,6 +9180,18 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) </para> </listitem> + <listitem> + <para> + <indexterm> + <primary><envar>PGPORTADDR</envar></primary> + </indexterm> + <envar>PGPORTADDR</envar> behaves the same as the <xref + linkend="libpq-connect-portaddr"/> connection parameter. + This can be set instead of or in addition to <envar>PGPORT</envar> + to connect through an intermediary listening on another port. + </para> + </listitem> + <listitem> <para> <indexterm> @@ -9580,6 +9665,10 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) the connection is a Unix-domain socket connection and the <literal>host</literal> parameter matches <application>libpq</application>'s default socket directory path. + The port field is matched to the <literal>port</literal> connection + parameter, never to the <literal>portaddr</literal> parameter; this way an + entry written for the server's own port keeps matching when the connection + is made through an intermediary listening on another port. In a standby server, a database field of <literal>replication</literal> matches streaming replication connections made to the primary server. The database field is of limited usefulness otherwise, because users have diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml index 3ec0a3c3b34..edf00ed7e99 100644 --- a/doc/src/sgml/ref/psql-ref.sgml +++ b/doc/src/sgml/ref/psql-ref.sgml @@ -990,9 +990,13 @@ INSERT INTO tbls1 VALUES ($1, $2) \parse stmt1 exception is that if the <replaceable>host</replaceable> setting is changed from its previous value using the positional syntax, any <replaceable>hostaddr</replaceable> setting present in the - existing connection's parameters is dropped. + existing connection's parameters is dropped; likewise, if either the + <replaceable>host</replaceable> or the <replaceable>port</replaceable> + setting is changed, any <replaceable>portaddr</replaceable> setting is + dropped. Also, any password used for the existing connection will be re-used - only if the user, host, and port settings are not changed. + only if the user, host, hostaddr, port, and portaddr settings are not + changed. When the command neither specifies nor reuses a particular parameter, the <application>libpq</application> default is used. </para> diff --git a/doc/src/sgml/regress.sgml b/doc/src/sgml/regress.sgml index c74941bfbf2..b6f4a2e0f40 100644 --- a/doc/src/sgml/regress.sgml +++ b/doc/src/sgml/regress.sgml @@ -343,6 +343,17 @@ make check-world PG_TEST_EXTRA='kerberos ldap ssl load_balance libpq_encryption' </listitem> </varlistentry> + <varlistentry> + <term><literal>portaddr</literal></term> + <listitem> + <para> + Runs the test <filename>src/interfaces/libpq/t/007_portaddr.pl</filename>. + The <literal>portaddr</literal> connection parameter only applies to + TCP connections, so this test opens a TCP/IP listen socket. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>regress_dump_restore</literal></term> <listitem> diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c index ee85c05a00d..7f4090e0d8d 100644 --- a/src/bin/psql/command.c +++ b/src/bin/psql/command.c @@ -3920,6 +3920,7 @@ do_connect(enum trivalue reuse_previous_specification, PQconninfoOption *cinfo; int nconnopts = 0; bool same_host = false; + bool same_port = false; char *password = NULL; char *client_encoding; bool success = true; @@ -4011,8 +4012,8 @@ do_connect(enum trivalue reuse_previous_specification, /* * Check whether connstring provides options affecting * password re-use. While any change in user, host, - * hostaddr, or port causes us to ignore the old - * connection's password, we don't force that for + * hostaddr, port, or portaddr causes us to ignore + * the old connection's password, we don't force that for * dbname, since passwords aren't database-specific. */ if (replci->val == NULL || @@ -4021,7 +4022,8 @@ do_connect(enum trivalue reuse_previous_specification, if (strcmp(replci->keyword, "user") == 0 || strcmp(replci->keyword, "host") == 0 || strcmp(replci->keyword, "hostaddr") == 0 || - strcmp(replci->keyword, "port") == 0) + strcmp(replci->keyword, "port") == 0 || + strcmp(replci->keyword, "portaddr") == 0) keep_password = false; } /* Also note whether connstring contains a password. */ @@ -4088,7 +4090,7 @@ do_connect(enum trivalue reuse_previous_specification, * management issues: PQconninfoFree would misbehave on Windows.) * However, to avoid dependencies on the order in which parameters * appear in the array, make a preliminary scan to set - * keep_password and same_host correctly. + * keep_password, same_host and same_port correctly. * * While any change in user, host, or port causes us to ignore the * old connection's password, we don't force that for dbname, @@ -4112,7 +4114,9 @@ do_connect(enum trivalue reuse_previous_specification, } else if (port && strcmp(ci->keyword, "port") == 0) { - if (!(ci->val && strcmp(port, ci->val) == 0)) + if (ci->val && strcmp(port, ci->val) == 0) + same_port = true; + else keep_password = false; } } @@ -4198,6 +4202,16 @@ do_connect(enum trivalue reuse_previous_specification, } else if (port && strcmp(ci->keyword, "port") == 0) values[paramnum++] = port; + else if (((host && !same_host) || (port && !same_port)) && + strcmp(ci->keyword, "portaddr") == 0) + { + /* + * An old portaddr describes where to reach a particular + * server, so drop it if either the host or the port value is + * changing. + */ + values[paramnum++] = NULL; + } /* If !keep_password, we unconditionally drop old password */ else if ((password || !keep_password) && strcmp(ci->keyword, "password") == 0) diff --git a/src/interfaces/libpq/fe-cancel.c b/src/interfaces/libpq/fe-cancel.c index 4b5945979c4..f9768a9c1c2 100644 --- a/src/interfaces/libpq/fe-cancel.c +++ b/src/interfaces/libpq/fe-cancel.c @@ -156,6 +156,12 @@ PQcancelCreate(PGconn *conn) if (!cancelConn->connhost[0].port) goto oom_error; } + if (originalHost.portaddr) + { + cancelConn->connhost[0].portaddr = strdup(originalHost.portaddr); + if (!cancelConn->connhost[0].portaddr) + goto oom_error; + } if (originalHost.password) { cancelConn->connhost[0].password = strdup(originalHost.password); diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 17c2288e9bc..69c38c6a367 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -243,6 +243,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Database-Port", "", 6, offsetof(struct pg_conn, pgport)}, + {"portaddr", "PGPORTADDR", NULL, NULL, + "Database-Port-Address", "", 6, + offsetof(struct pg_conn, pgportaddr)}, + {"client_encoding", "PGCLIENTENCODING", NULL, NULL, "Client-Encoding", "", 10, offsetof(struct pg_conn, client_encoding_initial)}, @@ -1403,6 +1407,48 @@ pqConnectOptions2(PGconn *conn) } } + /* + * Next, work out the port number to actually connect to for each host + * name, if portaddr was given. As for port above, these fields may be + * left null or empty; we will use the corresponding port field whenever + * we read such a portaddr field. + */ + if (conn->pgportaddr != NULL && conn->pgportaddr[0] != '\0') + { + int i; + char *s = conn->pgportaddr; + bool more = true; + + for (i = 0; i < conn->nconnhost && more; i++) + { + conn->connhost[i].portaddr = parse_comma_separated_list(&s, &more); + if (conn->connhost[i].portaddr == NULL) + goto oom_error; + } + + /* + * If exactly one portaddr was given, use it for every host. + * Otherwise, there must be exactly as many portaddrs as there were + * hosts. + */ + if (i == 1 && !more) + { + for (i = 1; i < conn->nconnhost; i++) + { + conn->connhost[i].portaddr = strdup(conn->connhost[0].portaddr); + if (conn->connhost[i].portaddr == NULL) + goto oom_error; + } + } + else if (more || i != conn->nconnhost) + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "could not match %d portaddr values to %d hosts", + count_comma_separated_elems(conn->pgportaddr), conn->nconnhost); + return false; + } + } + /* * If user name was not given, fetch it. (Most likely, the fetch will * fail, since the only way we get here is if pg_fe_getauthname() failed @@ -1459,7 +1505,10 @@ pqConnectOptions2(PGconn *conn) /* * Try to get a password for this host from file. We use host * for the hostname search key if given, else hostaddr (at - * least one of them is guaranteed nonempty by now). + * least one of them is guaranteed nonempty by now). Likewise, + * the port search key is always port, never portaddr: the + * search keys identify the server we mean to reach, not the + * address we happen to reach it at. */ const char *pwhost = conn->connhost[i].host; const char *password_errmsg = NULL; @@ -2448,7 +2497,9 @@ emitHostIdentityInfo(PGconn *conn, const char *host_addr) displayed_host = conn->connhost[conn->whichhost].hostaddr; else displayed_host = conn->connhost[conn->whichhost].host; - displayed_port = conn->connhost[conn->whichhost].port; + displayed_port = conn->connhost[conn->whichhost].portaddr; + if (displayed_port == NULL || displayed_port[0] == '\0') + displayed_port = conn->connhost[conn->whichhost].port; if (displayed_port == NULL || displayed_port[0] == '\0') displayed_port = DEF_PGPORT_STR; @@ -3069,6 +3120,25 @@ keep_going: /* We will come back to here until there is goto keep_going; } } + + /* + * If portaddr was given, that is the port we actually connect to, and + * port only serves to identify the server, just as host does when + * hostaddr is given. portaddr is ignored for Unix-domain socket + * connections, which are named by port. + */ + if (ch->type != CHT_UNIX_SOCKET && + ch->portaddr != NULL && ch->portaddr[0] != '\0') + { + if (!pqParseIntParam(ch->portaddr, &thisport, conn, "portaddr")) + goto error_return; + + if (thisport < 1 || thisport > 65535) + { + libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->portaddr); + goto keep_going; + } + } snprintf(portstr, sizeof(portstr), "%d", thisport); /* Use pg_getaddrinfo_all() to resolve the address */ @@ -5110,6 +5180,7 @@ freePGconn(PGconn *conn) free(conn->pghost); free(conn->pghostaddr); free(conn->pgport); + free(conn->pgportaddr); free(conn->connect_timeout); free(conn->pgtcp_user_timeout); free(conn->client_encoding_initial); @@ -5201,6 +5272,7 @@ pqReleaseConnHosts(PGconn *conn) free(conn->connhost[i].host); free(conn->connhost[i].hostaddr); free(conn->connhost[i].port); + free(conn->connhost[i].portaddr); if (conn->connhost[i].password != NULL) { explicit_bzero(conn->connhost[i].password, diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index 3f921207a14..3ccb063d453 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -361,6 +361,8 @@ typedef struct pg_conn_host char *hostaddr; /* host numeric IP address */ char *port; /* port number (if NULL or empty, use * DEF_PGPORT[_STR]) */ + char *portaddr; /* port number actually connected to, for TCP + * connections (if NULL or empty, use port) */ char *password; /* password for this host, read from the * password file; NULL if not sought or not * found in password file. */ @@ -383,6 +385,10 @@ struct pg_conn * precedence over pghost. */ char *pgport; /* the server's communication port number, or * a comma-separated list of ports */ + char *pgportaddr; /* the port number to connect to, or a + * comma-separated list of same. Takes + * precedence over pgport, except for + * Unix-domain socket connections. */ char *connect_timeout; /* connection timeout (numeric string) */ char *pgtcp_user_timeout; /* tcp user timeout (numeric string) */ char *client_encoding_initial; /* encoding to use */ diff --git a/src/interfaces/libpq/meson.build b/src/interfaces/libpq/meson.build index b0ae72167a1..9087d2972ec 100644 --- a/src/interfaces/libpq/meson.build +++ b/src/interfaces/libpq/meson.build @@ -161,6 +161,7 @@ tests += { 't/004_load_balance_dns.pl', 't/005_negotiate_encryption.pl', 't/006_service.pl', + 't/007_portaddr.pl', ], 'env': { 'with_ssl': ssl_library, diff --git a/src/interfaces/libpq/t/001_uri.pl b/src/interfaces/libpq/t/001_uri.pl index 64f257ae046..613b03e6aec 100644 --- a/src/interfaces/libpq/t/001_uri.pl +++ b/src/interfaces/libpq/t/001_uri.pl @@ -56,6 +56,12 @@ my @tests = ( q{host='example.com' hostaddr='63.1.2.4' (inet)}, q{}, ], + [ + q{postgresql://host:12345/db?portaddr=6000}, + q{dbname='db' host='host' port='12345' portaddr='6000' (inet)}, + q{}, + ], + [ q{postgresql://?portaddr=6000}, q{portaddr='6000' (local)}, q{}, ], [ q{postgresql://%68ost/}, q{host='host' (inet)}, q{}, ], [ q{postgresql://host/db?user=uri-user}, diff --git a/src/interfaces/libpq/t/007_portaddr.pl b/src/interfaces/libpq/t/007_portaddr.pl new file mode 100644 index 00000000000..5ecb573d8a7 --- /dev/null +++ b/src/interfaces/libpq/t/007_portaddr.pl @@ -0,0 +1,166 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# This tests the portaddr connection parameter, which separates the port that +# libpq actually connects to from the port that identifies the server. +# +# portaddr only applies to TCP connections, so the server has to listen on a +# TCP port here, which is why this test is not enabled by default. + +if (!$ENV{PG_TEST_EXTRA} || $ENV{PG_TEST_EXTRA} !~ /\bportaddr\b/) +{ + plan skip_all => + 'Potentially unsafe test portaddr not enabled in PG_TEST_EXTRA'; +} + +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->append_conf('postgresql.conf', "listen_addresses = '127.0.0.1'"); +$node->start; + +# The port the server really listens on, plus a port that nothing listens on. +# Reaching the server while naming the latter is only possible via portaddr. +my $realport = $node->port; +my $unusedport = PostgreSQL::Test::Cluster::get_free_port(); + +# Sanity check: without portaddr, the unused port is unreachable. +$node->connect_fails( + "host=127.0.0.1 port=$unusedport", + "connection to an unused port fails without portaddr", + expected_stderr => + qr/connection to server at "127\.0\.0\.1", port $unusedport failed/); + +# portaddr determines the port we connect to ... +$node->connect_ok( + "host=127.0.0.1 port=$unusedport portaddr=$realport", + "portaddr determines the port connected to", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); + +# ... while port still identifies the connection, as reported by PQport. +$node->connect_ok( + "host=127.0.0.1 port=$unusedport portaddr=$realport", + "PQport reports port, not portaddr", + sql => "\\echo :PORT", + expected_stdout => qr/^$unusedport$/); + +# An empty portaddr means "connect to port", the historical behavior. +$node->connect_ok( + "host=127.0.0.1 port=$realport portaddr=", + "empty portaddr falls back to port", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); + +# A connection failure reports the port we actually tried to reach. +$node->connect_fails( + "host=127.0.0.1 port=$realport portaddr=$unusedport", + "connection failure reports the portaddr port", + expected_stderr => + qr/connection to server at "127\.0\.0\.1", port $unusedport failed/); + +# Invalid values are rejected the same way port is. +$node->connect_fails( + "host=127.0.0.1 port=$realport portaddr=65536", + "portaddr must be a valid port number", + expected_stderr => qr/invalid port number: "65536"/); + +$node->connect_fails( + "host=127.0.0.1 port=$realport portaddr=notanumber", + "portaddr must be an integer", + expected_stderr => + qr/invalid integer value "notanumber" for connection option "portaddr"/); + +# The portaddr list must match the host list, unless it has a single element. +$node->connect_fails( + "host=127.0.0.1,127.0.0.1 port=$unusedport portaddr=$realport,$realport,$realport", + "portaddr list must match the host list", + expected_stderr => qr/could not match 3 portaddr values to 2 hosts/); + +# A single portaddr applies to every host. The first host here is a socket +# path that does not exist, so it fails and the second host is tried; that +# second host can only be reached if the lone portaddr was copied to it. +$node->connect_ok( + "host=/nonexistent,127.0.0.1 port=$unusedport portaddr=$realport", + "a single portaddr applies to all hosts", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); + +# An empty item in the list uses the corresponding port value. The first host +# is directed at the unused port and fails, so the second one is tried, and it +# can only succeed by falling back to its port. +$node->connect_ok( + "host=127.0.0.1,127.0.0.1 port=$unusedport,$realport portaddr=$unusedport,", + "an empty list item falls back to the corresponding port", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); + +# PGPORTADDR behaves the same as the parameter. +{ + local $ENV{PGPORTADDR} = $realport; + + $node->connect_ok( + "host=127.0.0.1 port=$unusedport", + "PGPORTADDR environment variable is honored", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); +} + +# portaddr is ignored for Unix-domain socket connections, which are named by +# port; naming an unused port there must not change anything. +if ($use_unix_sockets) +{ + $node->connect_ok( + $node->connstr('postgres') . " portaddr=$unusedport", + "portaddr is ignored for Unix-domain socket connections", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); +} + +# The password file is searched using port, never portaddr. This is the point +# of the parameter: an entry written for the server's own port keeps matching +# when the connection is made through an intermediary on another port. +$node->safe_psql('postgres', + "CREATE ROLE portaddr_role LOGIN PASSWORD 'secret'"); + +unlink($node->data_dir . '/pg_hba.conf'); +$node->append_conf('pg_hba.conf', "local all all trust"); +$node->append_conf('pg_hba.conf', + "host all portaddr_role 127.0.0.1/32 scram-sha-256"); +$node->append_conf('pg_hba.conf', "host all all 127.0.0.1/32 trust"); +$node->reload; + +my $pgpassfile = "${PostgreSQL::Test::Utils::tmp_check}/pgpass_portaddr"; +$ENV{PGPASSFILE} = $pgpassfile; + +# An entry keyed to the port that identifies the server matches, even though +# the connection is actually made to a different port. +unlink($pgpassfile); +append_to_file($pgpassfile, + "127.0.0.1:$unusedport:postgres:portaddr_role:secret\n"); +chmod 0600, $pgpassfile or die; + +$node->connect_ok( + "host=127.0.0.1 port=$unusedport portaddr=$realport user=portaddr_role", + "password file is searched using port", + sql => "SELECT 'authenticated'", + expected_stdout => qr/^authenticated$/); + +# Conversely, an entry keyed to the port actually connected to does not match. +unlink($pgpassfile); +append_to_file($pgpassfile, + "127.0.0.1:$realport:postgres:portaddr_role:secret\n"); +chmod 0600, $pgpassfile or die; + +$node->connect_fails( + "host=127.0.0.1 port=$unusedport portaddr=$realport user=portaddr_role", + "password file is not searched using portaddr", + expected_stderr => qr/no password supplied/); + +unlink($pgpassfile); +delete $ENV{PGPASSFILE}; + +done_testing(); diff --git a/src/test/perl/PostgreSQL/Test/Utils.pm b/src/test/perl/PostgreSQL/Test/Utils.pm index d3e6abf7a68..0e98a15a9f1 100644 --- a/src/test/perl/PostgreSQL/Test/Utils.pm +++ b/src/test/perl/PostgreSQL/Test/Utils.pm @@ -134,6 +134,7 @@ BEGIN PGKRBSRVNAME PGPASSFILE PGPASSWORD + PGPORTADDR PGREQUIREPEER PGREQUIRESSL PGSERVICE diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c index 21d00f792d2..6a19b50825e 100644 --- a/src/test/regress/pg_regress.c +++ b/src/test/regress/pg_regress.c @@ -837,6 +837,7 @@ initialize_environment(void) unsetenv("PGKRBSRVNAME"); unsetenv("PGPASSFILE"); unsetenv("PGPASSWORD"); + unsetenv("PGPORTADDR"); unsetenv("PGREQUIREPEER"); unsetenv("PGREQUIRESSL"); unsetenv("PGSERVICE"); @@ -893,6 +894,7 @@ initialize_environment(void) snprintf(s, sizeof(s), "%d", port); setenv("PGPORT", s, 1); + unsetenv("PGPORTADDR"); } if (user != NULL) setenv("PGUSER", user, 1); -- 2.43.0
^ permalink raw reply [nested|flat] 11+ messages in thread

* Re: [Proposal] add portaddr like hostaddr
  2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
@ 2026-08-24 19:23 ` Diego <mrstephenamell@gmail.com>
  2026-08-26 09:55   ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  0 siblings, 1 reply; 11+ messages in thread

From: Diego @ 2026-08-24 19:23 UTC (permalink / raw)
  To: pgsql-hackers@lists.postgresql.org

Hi Hackers!

Attached is v3 of the portaddr series.  No design changes; this is the
result of a self-review pass over v2, plus a rebase onto current master
(applies cleanly on 957d4eae52e).

Changes since v2:

* The new TAP test is now actually exercised by CI: portaddr was missing
   from PG_TEST_EXTRA in the CI workflow, so 007_portaddr.pl was skipped
   on every automated run.  Same treatment as load_balance got in
   7f5b19817ea.

* pg_isready now prints the port it actually probes when portaddr is
   given, the same way it already prefers hostaddr over host in its
   output.  Previously it probed portaddr but printed port.

* pg_upgrade refuses to run with PGPORTADDR set.  check_pghost_envvar()
   exists precisely to keep a stray libpq environment variable from
   silently redirecting pg_upgrade's connections, and PGPORTADDR is a
   redirect hazard of exactly that class (the series already scrubs it in
   pg_regress and PostgreSQL::Test::Utils for the same reason).

* pg_regress --use-existing now also drops an inherited PGPORTADDR when
   --host alone is overridden, not only --port, matching the series' own
   rule that a portaddr is stale when either half of the endpoint changes.

* Added the LIBPQ_HAS_PORTADDR feature macro for PQportaddr(), per the
   policy of shipping a feature-test macro with new libpq API (6991e774e).

* psql: the \conninfo "Port Address" row is no longer suppressed when a
   socket-path host is overridden into a TCP connection by hostaddr (the
   one corner where the row was hidden while portaddr was in effect), and
   the \connect success banner now reports the port address when it
   differs, mirroring what 6e5f8d489a did for hostaddr.

* Documentation touch-ups: PQport() now spells out the
   portaddr-without-port case (returns the default port number); the
   pgpass section states the default-port fallback for the port field,
   matching the adjacent host-field sentence; a \connect wording fix in
   the psql reference page.

* Commit message fixes, including removing the "ssh -L 127.0.0.1:0:..."
   example: OpenSSH rejects port 0 on -L (it is only valid for -R), which
   is exactly why the tools that need a dynamic local port pick a free
   one themselves right before opening the tunnel.

Thank you,
BR,
Diego

On 2026-08-13 15:49, Diego wrote:
> Hi Hackers!
>
> tl;dr: I want to add portaddr, like hostaddr, when the ssh tunnels 
> uses dynamic ports is a mess.
>        From my last attempt, [1], I undertand it sounds better in my 
> mind that the first try ;p
>
>
> Proposal
> --------
>
> Add a libpq connection parameter that says where the server is actually
> reached, so that port can go on identifying it -- exactly what hostaddr
> does for host.  The .pgpass lookup then stays on the logical (host, port)
> pair, and the password file code does not change at all.
>
> I do not have a strong opinion on the name: portaddr is the one that
> mirrors hostaddr, but I am happy to take suggestions.
>
> It is also easy to reason about for security: like hostaddr, it is an
> explicit, opt-in assertion by the user, and nothing changes unless it is
> given.
>
> This is not hypothetical. I ran into it myself while adding SSH tunnel
> support to pgcli (a widely used Postgres CLI): with the tunnel active, an
> explicit-port .pgpass entry never matches, because the lookup happens
> against the random local forwarding port. The user is prompted for a
> password even though the matching entry is right there, and only a
> wildcard port papers over it. Other tools hit the same wall:
>
> - pgAdmin 4: control the SSH tunnel local port for .pgpass matching
> https://github.com/pgadmin-org/pgadmin4/issues/6903
>
> - DBeaver: .pgpass looked up by 127.0.0.1 through an SSH tunnel
> https://github.com/dbeaver/dbeaver/issues/16499
>
> - pgcli: SSH tunnel rewrites the port before the .pgpass lookup (myself)
> https://github.com/dbcli/pgcli/pull/1546
>
>
> Recap, since the approach changed
> ---------------------------------
>
> The first version of this proposal added a parameter that affected only
> the .pgpass lookup.  Christoph pointed out [2] that for a tunnel you open
> by hand, with a fixed local port, you can simply write that port into
> .pgpass.  That is correct, and I withdrew that part of the motivation.
>
> What remains is the case where the local port is not known when the
> password file is written, because the tunnel is not opened by hand.
> Clients that open it for you bind the local end to port 0 and let the
> kernel choose.  pgcli, the case I ran into, does exactly that: it hands
> sshtunnel a local bind address with no port in it,
>
>     "local_bind_address": ("127.0.0.1",),
>
> and only afterwards asks which port it got,
>
>     port = self.ssh_tunnel.local_bind_ports[0]
>
> which it then substitutes into the connection string.  The forwarding
> port is different on every run, and those two lines are precisely what
> breaks the .pgpass lookup.  pgAdmin 4 and DBeaver open their own tunnels
> the same way, which is what the two reports above are about, and outside
> SSH the same shape shows up in kubectl port-forward, where ":5432" means
> "listen on a random local port".
>
> There is no port you can write into .pgpass in advance.
>
> (Plain ssh(1) cannot even express this: OpenSSH rejects port 0 on -L and
> accepts it only for -R, so the wrappers pick a free local port
> themselves and pass it to -L.  Same outcome for .pgpass.)
>
> The model
> ---------
>
> libpq already allows the host that identifies a server to differ from the
> address it is reached at:
>
>     host identifies the server, hostaddr is where we connect,
>     and the password file is searched by host.
>
> v2 does the same for ports, instead of adding a password-file-only knob:
>
>     port identifies the server, portaddr is where we connect,
>     and the password file is searched by port.
>
> The tunnel case is then spelled
>
>     host=db.example.com hostaddr=127.0.0.1 port=5432 portaddr=39907
>
> and the password file entry is the one a direct connection already uses:
>
>     db.example.com:5432:appdb:alice:secret
>
> What I like about this shape is that the password file code does not
> change at all.  passwordFromFile() already receives connhost[i].port, so
> keeping portaddr in a separate field leaves the lookup logical by
> construction.  That is the same reasoning as e3f99e03e2e, which settled
> that the .pgpass host key is host and not hostaddr.
>
> The patches
> -----------
>
> Both patches are attached.  They apply cleanly on master as of
> 957d4eae52e.
>
> 0001  libpq: add portaddr, the port equivalent of hostaddr
>       The parameter, the PGPORTADDR environment variable, documentation,
>       and a TAP test.  It also contains a psql \connect fix, see below.
>
> 0002  libpq: add PQportaddr(), and show the port address in psql \conninfo
>       The accessor mirroring PQhostaddr(), and the psql display. This one
>       is separable: if the list does not want it, 0001 stands on its own.
>
> The new test, src/interfaces/libpq/t/007_portaddr.pl, needs the server to
> listen on TCP, so it is skipped unless PG_TEST_EXTRA lists portaddr:
>
>     make check-world PG_TEST_EXTRA=portaddr
>
> The environment variable works for meson builds as well.  Without it the
> test plans skip_all and nothing else in the suite is affected.
>
> Decisions I made, and where I would like guidance
> -------------------------------------------------
>
> * portaddr applies to TCP only, and is ignored for Unix-domain socket
>   connections, whose socket file name is built from port. hostaddr does
>   not apply to those either.
>
> * The list semantics follow port rather than hostaddr: a single portaddr
>   applies to every host, otherwise the element count must match the host
>   count, and an empty item means "use the corresponding port". hostaddr
>   has to match exactly because it determines the number of hosts;
>   portaddr does not.
>
> * port is still parsed and range-checked even when portaddr overrides it.
>   hostaddr does not validate host, but any string is a plausible host
>   name, whereas a port has a syntax; silently accepting a bad value that
>   then becomes the password file search key seemed worse than erroring
>   out.
>
> * PQport() keeps returning port, mirroring PQhost(), which returns host
>   and not hostaddr.  Its documentation promised "the port actually
>   connected to", so I reworded it, and 0002 adds PQportaddr() for the
>   actual port.
>
> * Connection failure messages report the port actually attempted, since
>   "connection to server at ..., port N failed" is about where we tried to
>   go.
>
> * psql's \connect drops an inherited hostaddr when the host argument
>   changes.  portaddr needs the same treatment, and it has to key on both:
>   a portaddr describes where to reach one particular server, so 0001 drops
>   it when either the host or the port argument changes.  Without that,
>   "\c - - otherhost" would keep tunnelling to the old portaddr on a
>   different machine.  This is in 0001 because leaving it out is a bug, not
>   a missing polish item.
>
> * PGPORTADDR is added to the environment variables cleared by pg_regress
>   and PostgreSQL::Test::Utils, next to PGHOSTADDR, which is scrubbed there
>   for exactly the same reason: it would silently redirect test connections
>   away from the temporary cluster.
>
> * The new TAP test has to make the server listen on TCP, since portaddr
>   does not apply to Unix-domain sockets.  Following ssl, kerberos, 
> ldap and
>   load_balance, it runs only when PG_TEST_EXTRA lists portaddr, and
>   regress.sgml documents the new value.  I am not attached to the name, or
>   to having a keyword of its own rather than folding it into an existing
>   one.
>
> The POC #1 first flight
> -----------------------
>
> daf@t:postgres$ test=/home/daf/scripts/postgres/portaddr-demo
> daf@t:postgres$ BIN_CON="$test/con-el-patch/usr/local/bin"
> daf@t:postgres$ 
> LIB_CON="$test/con-el-patch/usr/local/lib/x86_64-linux-gnu"
> daf@t:postgres$ PSQL_CON="$test/con-el-patch/usr/local/bin/psql"
> daf@t:postgres$ LIB_SIN="$test/sin-patch/usr/local/lib/x86_64-linux-gnu"
> daf@t:postgres$ PSQL_SIN="$test/sin-patch/usr/local/bin/psql"
> daf@t:postgres$ unset PGPASSWORD PGPORTADDR
> daf@t:postgres$ export LD_LIBRARY_PATH="$LIB_CON"
> daf@t:postgres$ export PGDATA=/tmp/pgd-test-portaddr
> daf@t:postgres$ export PGPASSFILE=/tmp/pgpass-test-portaddr
> daf@t:postgres$
> daf@t:postgres$ # init
> daf@t:postgres$
> daf@t:postgres$ "$BIN_CON/initdb" -D "$PGDATA" -U postgres -A trust 
> --no-sync
> The files belonging to this database system will be owned by user "daf".
> This user must also own the server process.
>
> The database cluster will be initialized with locale "C.UTF-8".
> The default database encoding has accordingly been set to "UTF8".
> The default text search configuration will be set to "english".
>
> Data page checksums are enabled.
>
> creating directory /tmp/pgd-test-portaddr ... ok
> creating subdirectories ... ok
> selecting dynamic shared memory implementation ... posix
> selecting default "max_connections" ... 100
> selecting default "shared_buffers" ... 128MB
> selecting default time zone ... America/Argentina/Buenos_Aires
> creating configuration files ... ok
> running bootstrap script ... ok
> performing post-bootstrap initialization ... ok
>
> Sync to disk skipped.
> The data directory might become corrupt if the operating system crashes.
>
> Success. You can now start the database server using:
>
> /home/daf/scripts/postgres/portaddr-demo/con-el-patch/usr/local/bin/pg_ctl 
> -D /tmp/pgd-test-portaddr -l logfile start
>
> daf@t:postgres$ printf 'local all all trust\nhost all all 127.0.0.1/32 
> scram-sha-256\n' > "$PGDATA/pg_hba.conf"
> daf@t:postgres$ cat "$PGDATA/pg_hba.conf"
> local all all trust
> host all all 127.0.0.1/32 scram-sha-256
> daf@t:postgres$ "$BIN_CON/pg_ctl" -D "$PGDATA" -o "-p 5441 -c 
> listen_addresses=127.0.0.1" -w start
> waiting for server to start....2026-08-13 14:23:31.316 -03 [1018117] 
> LOG:  starting PostgreSQL 20devel on x86_64-linux, compiled by 
> gcc-12.2.0, 64-bit
> 2026-08-13 14:23:31.316 -03 [1018117] LOG:  listening on IPv4 address 
> "127.0.0.1", port 5441
> 2026-08-13 14:23:31.319 -03 [1018117] LOG:  listening on Unix socket 
> "/tmp/.s.PGSQL.5441"
> 2026-08-13 14:23:31.325 -03 [1018122] LOG:  database system was shut 
> down at 2026-08-13 14:22:49 -03
> 2026-08-13 14:23:31.330 -03 [1018117] LOG:  database system is ready 
> to accept connections
>  done
> server started
> daf@t:postgres$ "$BIN_CON/psql" -X -p 5441 -U postgres -h /tmp -d 
> postgres -c "create role tuser login password 'sekret';"
> CREATE ROLE
> daf@t:postgres$
> daf@t:postgres$ echo "127.0.0.1:5440:postgres:tuser:sekret" > 
> "$PGPASSFILE"
> daf@t:postgres$ chmod 600 "$PGPASSFILE"
> daf@t:postgres$
>
> daf@t:postgres$
> daf@t:postgres$ cat "$PGPASSFILE"
> 127.0.0.1:5440:postgres:tuser:sekret
> daf@t:postgres$
> daf@t:postgres$ # 1) Original without patch, FAIL -> bug: .pgpass not 
> match
> LD_LIBRARY_PATH="$LIB_SIN" "$PSQL_SIN" -X -w "host=127.0.0.1 port=5441 
> user=tuser dbname=postgres" -tAc "select 'AUTENTICO-OK'"
> psql: error: connection to server at "127.0.0.1", port 5441 failed: 
> fe_sendauth: no password supplied
> daf@t:postgres$
> daf@t:postgres$ # 2) without patch + portaddr -> FAIL
> LD_LIBRARY_PATH="$LIB_SIN" "$PSQL_SIN" -X -w "host=127.0.0.1 port=5440 
> portaddr=5441 user=tuser dbname=postgres" -tAc "select 'AUTENTICO-OK'"
> psql: error: invalid connection option "portaddr"
> daf@t:postgres$
> daf@t:postgres$ # 3) WITH patch + portaddr -> AUTENTICA (same line as 
> #2, different libpq)
> LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 port=5440 
> portaddr=5441 user=tuser dbname=postgres" -tAc "select 'AUTENTICO-OK'"
> AUTENTICO-OK
> daf@t:postgres$
> daf@t:postgres$ # 4) WITH patch, no portaddr -> FAIL, default not changed
> LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 port=5441 
> user=tuser dbname=postgres" -tAc "select 'AUTENTICO-OK'"
> psql: error: connection to server at "127.0.0.1", port 5441 failed: 
> fe_sendauth: no password supplied
> daf@t:postgres$
> daf@t:postgres$ # 5) WITH patch, env var instead of the parameter -> 
> AUTENTICA
> PGPORTADDR=5441 LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w 
> "host=127.0.0.1 port=5440 user=tuser dbname=postgres" -tAc "select 
> 'AUTENTICO-OK'"
> AUTENTICO-OK
> daf@t:postgres$ # 6) WITH patch, what the client sees -> Server Port 
> 5440 / Port Address 5441
> LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 port=5440 
> portaddr=5441 user=tuser dbname=postgres" -c "\conninfo"
>       Connection Information
>       Parameter       |   Value
> ----------------------+-----------
>  Database             | postgres
>  Client User          | tuser
>  Host                 | 127.0.0.1
>  Server Port          | 5440
>  Port Address         | 5441
>  Options              |
>  Protocol Version     | 3.2
>  Password Used        | true
>  GSSAPI Authenticated | false
>  Backend PID          | 1018919
>  SSL Connection       | false
>  Superuser            | off
>  Hot Standby          | off
> (13 rows)
>
> daf@t:postgres$
> daf@t:postgres$ 2026-08-13 14:28:31.428 -03 [1018120] LOG: checkpoint 
> starting: time
> 2026-08-13 14:28:36.176 -03 [1018120] LOG:  checkpoint complete: time: 
> wrote 47 buffers (0.3%), wrote 3 SLRU buffers; 0 WAL file(s) added, 0 
> removed, 0 recycled; write=4.713 s, sync=0.024 s, total=4.748 s; sync 
> files=15, longest=0.018 s, average=0.002 s; distance=345 kB, 
> estimate=345 kB; lsn=0/017D4910, redo lsn=0/017D4878
>
> "$BIN_CON/pg_ctl" -D "$PGDATA" -m immediate stop
> waiting for server to shut down....2026-08-13 14:29:17.551 -03 
> [1018117] LOG:  received immediate shutdown request
> 2026-08-13 14:29:17.563 -03 [1018117] LOG:  database system is shut down
>  done
> server stopped
>
> The POC #2 withreal case
> ------------------------
>
>
> daf@t:postgres$ # ---- setup
> daf@t:postgres$ test=/home/daf/scripts/postgres/portaddr-demo
> daf@t:postgres$ 
> LIB_CON="$test/con-el-patch/usr/local/lib/x86_64-linux-gnu"
> daf@t:postgres$ PSQL_CON="$test/con-el-patch/usr/local/bin/psql"
> daf@t:postgres$ LIB_SIN="$test/sin-patch/usr/local/lib/x86_64-linux-gnu"
> daf@t:postgres$ PSQL_SIN="$test/sin-patch/usr/local/bin/psql"
> daf@t:postgres$ SSH_HOST=beta
> daf@t:postgres$ REAL_HOST=beta.xxxx.yyyy.zzz
> daf@t:postgres$ REAL_PORT=55432
> daf@t:postgres$ LOCAL_PORT=5533
> daf@t:postgres$ SSH_SOCK=/tmp/portaddr-beta-ssh.sock
> daf@t:postgres$
> daf@t:postgres$ unset PGPASSWORD PGPORTADDR
> daf@t:postgres$ export PGPASSFILE=/tmp/pgpass-demo-portaddr-beta
> daf@t:postgres$
> daf@t:postgres$ ssh -M -S "$SSH_SOCK" -f -N "$SSH_HOST"
> daf@t:postgres$ ssh -S "$SSH_SOCK" -O forward -L 
> $LOCAL_PORT:localhost:$REAL_PORT "$SSH_HOST"
> daf@t:postgres$ ss -ltn | grep $LOCAL_PORT
> LISTEN 0      128        127.0.0.1:5533       0.0.0.0:*
> daf@t:postgres$
> daf@t:postgres$ cat "$PGPASSFILE"
> 127.0.0.1:55432:*:daf:sekret
> daf@t:postgres$ chmod 600 "$PGPASSFILE"
> daf@t:postgres$
> daf@t:postgres$
> daf@t:postgres$ # 1) Original without patch, FAIL -> bug: .pgpass no 
> matchea el puerto del tunel
> LD_LIBRARY_PATH="$LIB_SIN" "$PSQL_SIN" -X -w "host=127.0.0.1 
> port=$LOCAL_PORT user=daf dbname=daf" -tAc "select 'AUTENTICO-OK'"
> psql: error: connection to server at "127.0.0.1", port 5533 failed: 
> fe_sendauth: no password supplied
> daf@t:postgres$
> daf@t:postgres$ # 2) without patch + portaddr -> FAIL
> LD_LIBRARY_PATH="$LIB_SIN" "$PSQL_SIN" -X -w "host=127.0.0.1 
> port=$REAL_PORT portaddr=$LOCAL_PORT user=daf dbname=daf" -tAc "select 
> 'AUTENTICO-OK'"
> psql: error: invalid connection option "portaddr"
> daf@t:postgres$
> daf@t:postgres$ # 3) WITH patch + portaddr -> AUTENTICA (same like #2, 
> other libpq)
> LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 
> port=$REAL_PORT portaddr=$LOCAL_PORT user=daf dbname=daf" -tAc "select 
> 'AUTENTICO-OK'"
> AUTENTICO-OK
> daf@t:postgres$ # 4) WITH patch, no portaddr -> FAIL, same default
> LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 
> port=$LOCAL_PORT user=daf dbname=daf" -tAc "select 'AUTENTICO-OK'"
> psql: error: connection to server at "127.0.0.1", port 5533 failed: 
> fe_sendauth: no password supplied
> daf@t:postgres$
> daf@t:postgres$ # 5) WITH patch, env var en vez del parametro -> AUTENTICA
> PGPORTADDR=$LOCAL_PORT LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w 
> "host=127.0.0.1 port=$REAL_PORT user=daf dbname=daf" -tAc "select 
> 'AUTENTICO-OK'"
> AUTENTICO-OK
> daf@t:postgres$
> daf@t:postgres$ # 6) WITH patch, lo que ve el cliente -> Server Port 
> 55432 / Port Address 5533 / Password Used true
> LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=127.0.0.1 
> port=$REAL_PORT portaddr=$LOCAL_PORT user=daf dbname=daf" -c "\conninfo"
>       Connection Information
>       Parameter       |   Value
> ----------------------+-----------
>  Database             | daf
>  Client User          | daf
>  Host                 | 127.0.0.1
>  Server Port          | 55432
>  Port Address         | 5533
>  Options              |
>  Protocol Version     | 3.0
>  Password Used        | true
>  GSSAPI Authenticated | false
>  Backend PID          | 290199
>  SSL Connection       | false
>  Superuser            | on
>  Hot Standby          | off
> (13 rows)
>
> daf@t:postgres$
> daf@t:postgres$
> # ---------------------------------------------------------------
> # 7) THE MAIN CASE: the full symmetry, using your REAL ~/.pgpass untouched
> #
> #   host     = beta.xxxx.yyyy.zzz   hostaddr = 127.0.0.1
> #   port     = 55432                      portaddr = 5533
> #
> # The LOGICAL pair (host, port) is how you know the server, and what 
> the .pgpass
> # lookup uses; the PHYSICAL pair (hostaddr, portaddr) is where the 
> socket really
> # goes. Without portaddr, hostaddr alone is not enough: you can lie 
> about the
> # host, but the port still gives you away.
>
> daf@t:postgres$ unset PGPASSFILE
> daf@t:postgres$
> daf@t:postgres$ # without patch: hostaddr has been there for years, 
> but the lookup still uses the tunnel port -> FAILS
> LD_LIBRARY_PATH="$LIB_SIN" "$PSQL_SIN" -X -w "host=$REAL_HOST 
> hostaddr=127.0.0.1 port=$LOCAL_PORT user=daf dbname=daf" -tAc "select 
> 'AUTENTICO-OK'"
> psql: error: connection to server at "127.0.0.1", port 5533 failed: 
> fe_sendauth: no password supplied
> daf@t:postgres$
> daf@t:postgres$ # WITH patch: (host,port) for the lookup + 
> (hostaddr,portaddr) for the socket -> AUTHENTICATES
> LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=$REAL_HOST 
> hostaddr=127.0.0.1 port=$REAL_PORT portaddr=$LOCAL_PORT user=daf 
> dbname=daf" -tAc "select 'AUTENTICO-OK'"
> AUTENTICO-OK
> daf@t:postgres$
> daf@t:postgres$ # \conninfo shows the 4 rows together: Host / Host 
> Address / Server Port / Port Address
> LD_LIBRARY_PATH="$LIB_CON" "$PSQL_CON" -X -w "host=$REAL_HOST 
> hostaddr=127.0.0.1 port=$REAL_PORT portaddr=$LOCAL_PORT user=daf 
> dbname=daf" -c "\conninfo"
>              Connection Information
>       Parameter       |          Value
> ----------------------+--------------------------
>  Database             | daf
>  Client User          | daf
>  Host                 | beta.xxxx.yyyy.zzz
>  Host Address         | 127.0.0.1
>  Server Port          | 55432
>  Port Address         | 5533
>  Options              |
>  Protocol Version     | 3.0
>  Password Used        | true
>  GSSAPI Authenticated | false
>  Backend PID          | 290265
>  SSL Connection       | false
>  Superuser            | on
>  Hot Standby          | off
> (14 rows)
>
>
> And that's all folks.
> Please, feel free to send feedback.
>
>
> [1] 
> https://www.postgresql.org/message-id/flat/001a6f1d-4adb-42b2-8bf6-44154ed0ab97%40gmail.com
> [2] https://postgr.es/m/ak6FwxXWcBTvvpPo@msg.df7cb.de
>
>
>
> Thank you all,
> BR,
> Diego 

Attachments: download all (2 files, .tar.gz)

v3-0001-libpq-Add-portaddr-the-port-equivalent-of-hostadd.patch (text/x-patch, 32.7K) download From 8da96cd1e9e4d63a69bf928b25c0bfd7046d4055 Mon Sep 17 00:00:00 2001 From: Diego <mrstephenamell@gmail.com> Date: Mon, 27 Jul 2026 14:06:35 -0300 Subject: [PATCH v3 1/2] libpq: Add portaddr, the port equivalent of hostaddr libpq has long allowed the host name that identifies a server to differ from the address actually connected to: host names the server, hostaddr gives the address to reach it at, and the password file is searched using host. Ports have no such separation. The port parameter is both the port connected to and the port used as the password file search key, so a connection made through an intermediary listening on a different port -- an SSH tunnel, a connection proxy -- cannot use a password file entry written for the server itself. Writing the intermediary's port into the password file works when that port is fixed and known ahead of time, but not when it is assigned at connection time. Clients that open tunnels themselves (pgcli, pgAdmin, DBeaver) bind the local end to port 0 and let the kernel choose, and cloud database proxies and "kubectl port-forward" behave the same way. There the local port is unknown when the password file is written, and differs between sessions. Add a portaddr parameter, and a PGPORTADDR environment variable, that completes the model: when portaddr is given it is the port connected to, and port only identifies the server, exactly as host does when hostaddr is given. The password file lookup therefore keeps using port. Like hostaddr, portaddr applies only to TCP connections; it is ignored for Unix-domain sockets, whose socket file name is determined by port. psql's \connect drops a hostaddr inherited from the previous connection when the host argument changes. Do the same for portaddr when either the host or the port argument changes, so that reconnecting elsewhere is not silently redirected through the old address. pg_isready reports the port actually probed, the same way it already reports hostaddr in preference to host. PGPORTADDR is added to the environment variables cleared by pg_regress and PostgreSQL::Test::Utils, since like PGHOSTADDR it would otherwise redirect test connections away from the temporary cluster; pg_regress also drops it when --host or --port overrides the environment of an existing installation. pg_upgrade refuses to run with PGPORTADDR set, just as it refuses a non-local PGHOST. The new TAP test opens a TCP listen socket, so it runs only when portaddr is listed in PG_TEST_EXTRA; the CI workflow enables it. Behavior is unchanged when portaddr is not specified. Discussion: https://postgr.es/m/001a6f1d-4adb-42b2-8bf6-44154ed0ab97@gmail.com --- .github/workflows/pg-ci.yml | 2 +- doc/src/sgml/libpq.sgml | 101 ++++++++++++++- doc/src/sgml/ref/psql-ref.sgml | 8 +- doc/src/sgml/regress.sgml | 11 ++ src/bin/pg_upgrade/server.c | 17 ++- src/bin/psql/command.c | 24 +++- src/bin/scripts/pg_isready.c | 10 +- src/interfaces/libpq/fe-cancel.c | 6 + src/interfaces/libpq/fe-connect.c | 76 ++++++++++- src/interfaces/libpq/libpq-int.h | 6 + src/interfaces/libpq/meson.build | 1 + src/interfaces/libpq/t/001_uri.pl | 6 + src/interfaces/libpq/t/007_portaddr.pl | 166 +++++++++++++++++++++++++ src/test/perl/PostgreSQL/Test/Utils.pm | 1 + src/test/regress/pg_regress.c | 3 + 15 files changed, 422 insertions(+), 16 deletions(-) create mode 100644 src/interfaces/libpq/t/007_portaddr.pl diff --git a/.github/workflows/pg-ci.yml b/.github/workflows/pg-ci.yml index a2629c8335a..b7cba693eda 100644 --- a/.github/workflows/pg-ci.yml +++ b/.github/workflows/pg-ci.yml @@ -67,7 +67,7 @@ env: PGCTLTIMEOUT: 120 # avoids spurious failures during parallel tests TEMP_CONFIG: ${{ github.workspace }}/src/tools/ci/pg_ci_base.conf - PG_TEST_EXTRA: kerberos ldap ssl libpq_encryption load_balance oauth + PG_TEST_EXTRA: kerberos ldap ssl libpq_encryption load_balance oauth portaddr # Postgres config args for the meson builds, shared between all meson tasks # except the 'SanityCheck' task diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 7d3c3bb66d8..6b3adb2e449 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -1085,12 +1085,14 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname <para> It is possible to specify multiple hosts to connect to, so that they are tried in the given order. In the Keyword/Value format, the <literal>host</literal>, - <literal>hostaddr</literal>, and <literal>port</literal> options accept comma-separated + <literal>hostaddr</literal>, <literal>port</literal>, and + <literal>portaddr</literal> options accept comma-separated lists of values. The same number of elements must be given in each option that is specified, such that e.g., the first <literal>hostaddr</literal> corresponds to the first host name, the second <literal>hostaddr</literal> corresponds to the second host name, and so - forth. As an exception, if only one <literal>port</literal> is specified, it + forth. As an exception, if only one <literal>port</literal> + or <literal>portaddr</literal> is specified, it applies to all the hosts. </para> @@ -1251,6 +1253,73 @@ postgresql://%2Fvar%2Flib%2Fpostgresql/dbname </listitem> </varlistentry> + <varlistentry id="libpq-connect-portaddr" xreflabel="portaddr"> + <term><literal>portaddr</literal></term> + <listitem> + <para> + Port number to actually connect to at the server host. When a nonempty + string is specified for this parameter, it determines where the + connection is made, and <xref linkend="libpq-connect-port"/> only + identifies the server &mdash; much as + <xref linkend="libpq-connect-host"/> still identifies the server when + <xref linkend="libpq-connect-hostaddr"/> is given. If this parameter + is not specified, the value of <literal>port</literal> is connected to, + which is the historical behavior. This parameter is ignored for + Unix-domain socket connections, whose socket file name is always + determined by <literal>port</literal>. + </para> + + <para> + Using <literal>portaddr</literal> allows the connection to be made + through an intermediary listening on a different port, such as an + <acronym>SSH</acronym> tunnel or a connection proxy, while the other + connection parameters continue to describe the server itself. In + particular, the port used to identify the connection in a password file + (see <xref linkend="libpq-pgpass"/>) is <literal>port</literal>, not + <literal>portaddr</literal>, so a password file entry written for the + server's own port keeps matching even when the intermediary listens on + a port that is not known in advance. The following rules are used: + <itemizedlist> + <listitem> + <para> + If <literal>port</literal> is specified + without <literal>portaddr</literal>, the connection is made to + <literal>port</literal>, which also identifies the connection. + </para> + </listitem> + <listitem> + <para> + If <literal>portaddr</literal> is specified + without <literal>port</literal>, the value + for <literal>portaddr</literal> gives the port to connect to, and + the default port number identifies the connection. + </para> + </listitem> + <listitem> + <para> + If both <literal>port</literal> and <literal>portaddr</literal> are + specified, the value for <literal>portaddr</literal> gives the port + to connect to. The value for <literal>port</literal> is used only + to identify the connection. + </para> + </listitem> + </itemizedlist> + Note that authentication is likely to fail if <literal>port</literal> + is not the port of the server reached + at <literal>portaddr</literal>, since the password file entry that is + selected will then be the wrong one. + </para> + + <para> + A comma-separated list of <literal>portaddr</literal> values is also + accepted, in which case it must have the same length as the host list, + or it may specify a single value to be used for all hosts. An empty + item in the list causes the corresponding <literal>port</literal> value + to be used. See <xref linkend="libpq-multiple-hosts"/> for details. + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-connect-dbname" xreflabel="dbname"> <term><literal>dbname</literal></term> <listitem> @@ -2766,8 +2835,15 @@ char *PQport(const PGconn *conn); </para> <para> - If multiple ports were specified in the connection parameters, - <xref linkend="libpq-PQport"/> returns the port actually connected to. + If the connection parameters specified both <literal>port</literal> and + <literal>portaddr</literal>, then <xref linkend="libpq-PQport"/> will + return the <literal>port</literal> information. If + <literal>portaddr</literal> was specified without + <literal>port</literal>, then the default port number is returned, + since that is what identifies the server. If multiple ports were + specified in the connection parameters, + <xref linkend="libpq-PQport"/> returns the port of the host actually + connected to. </para> <para> @@ -9107,6 +9183,18 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) </para> </listitem> + <listitem> + <para> + <indexterm> + <primary><envar>PGPORTADDR</envar></primary> + </indexterm> + <envar>PGPORTADDR</envar> behaves the same as the <xref + linkend="libpq-connect-portaddr"/> connection parameter. + This can be set instead of or in addition to <envar>PGPORT</envar> + to connect through an intermediary listening on another port. + </para> + </listitem> + <listitem> <para> <indexterm> @@ -9580,6 +9668,11 @@ myEventProc(PGEventId evtId, void *evtInfo, void *passThrough) the connection is a Unix-domain socket connection and the <literal>host</literal> parameter matches <application>libpq</application>'s default socket directory path. + The port field is matched to the <literal>port</literal> connection + parameter if that is specified, otherwise to the default port number; + it is never matched to the <literal>portaddr</literal> parameter. This + way an entry written for the server's own port keeps matching when the + connection is made through an intermediary listening on another port. In a standby server, a database field of <literal>replication</literal> matches streaming replication connections made to the primary server. The database field is of limited usefulness otherwise, because users have diff --git a/doc/src/sgml/ref/psql-ref.sgml b/doc/src/sgml/ref/psql-ref.sgml index 016103aca8a..555b0215fd6 100644 --- a/doc/src/sgml/ref/psql-ref.sgml +++ b/doc/src/sgml/ref/psql-ref.sgml @@ -990,9 +990,13 @@ INSERT INTO tbls1 VALUES ($1, $2) \parse stmt1 exception is that if the <replaceable>host</replaceable> setting is changed from its previous value using the positional syntax, any <replaceable>hostaddr</replaceable> setting present in the - existing connection's parameters is dropped. + existing connection's parameters is dropped; likewise, if either the + <replaceable>host</replaceable> or the <replaceable>port</replaceable> + setting is changed that way, any <replaceable>portaddr</replaceable> + setting is dropped. Also, any password used for the existing connection will be re-used - only if the user, host, and port settings are not changed. + only if the user, host, hostaddr, port, and portaddr settings are not + changed. When the command neither specifies nor reuses a particular parameter, the <application>libpq</application> default is used. </para> diff --git a/doc/src/sgml/regress.sgml b/doc/src/sgml/regress.sgml index c74941bfbf2..b6f4a2e0f40 100644 --- a/doc/src/sgml/regress.sgml +++ b/doc/src/sgml/regress.sgml @@ -343,6 +343,17 @@ make check-world PG_TEST_EXTRA='kerberos ldap ssl load_balance libpq_encryption' </listitem> </varlistentry> + <varlistentry> + <term><literal>portaddr</literal></term> + <listitem> + <para> + Runs the test <filename>src/interfaces/libpq/t/007_portaddr.pl</filename>. + The <literal>portaddr</literal> connection parameter only applies to + TCP connections, so this test opens a TCP/IP listen socket. + </para> + </listitem> + </varlistentry> + <varlistentry> <term><literal>regress_dump_restore</literal></term> <listitem> diff --git a/src/bin/pg_upgrade/server.c b/src/bin/pg_upgrade/server.c index 7da9dffe585..9784b71f4bc 100644 --- a/src/bin/pg_upgrade/server.c +++ b/src/bin/pg_upgrade/server.c @@ -314,7 +314,8 @@ stop_postmaster(bool in_atexit) /* * check_pghost_envvar() * - * Tests that PGHOST does not point to a non-local server + * Tests that PGHOST does not point to a non-local server, and that a stray + * PGPORTADDR cannot redirect our connections to some other port */ void check_pghost_envvar(void) @@ -343,6 +344,20 @@ check_pghost_envvar(void) pg_fatal("libpq environment variable %s has a non-local server value: %s", option->envvar, value); } + + /* + * There is no acceptable value for PGPORTADDR: it would redirect + * connections away from the ports pg_upgrade chooses for the old and + * new clusters. + */ + if (option->envvar && strcmp(option->envvar, "PGPORTADDR") == 0) + { + const char *value = getenv(option->envvar); + + if (value && strlen(value) > 0) + pg_fatal("libpq environment variable %s must not be set when running pg_upgrade", + option->envvar); + } } /* Free the memory that libpq allocated on our behalf */ diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c index 190c5c6f77a..267c8c7d8b8 100644 --- a/src/bin/psql/command.c +++ b/src/bin/psql/command.c @@ -3924,6 +3924,7 @@ do_connect(enum trivalue reuse_previous_specification, PQconninfoOption *cinfo; int nconnopts = 0; bool same_host = false; + bool same_port = false; char *password = NULL; char *client_encoding; bool success = true; @@ -4015,8 +4016,8 @@ do_connect(enum trivalue reuse_previous_specification, /* * Check whether connstring provides options affecting * password re-use. While any change in user, host, - * hostaddr, or port causes us to ignore the old - * connection's password, we don't force that for + * hostaddr, port, or portaddr causes us to ignore + * the old connection's password, we don't force that for * dbname, since passwords aren't database-specific. */ if (replci->val == NULL || @@ -4025,7 +4026,8 @@ do_connect(enum trivalue reuse_previous_specification, if (strcmp(replci->keyword, "user") == 0 || strcmp(replci->keyword, "host") == 0 || strcmp(replci->keyword, "hostaddr") == 0 || - strcmp(replci->keyword, "port") == 0) + strcmp(replci->keyword, "port") == 0 || + strcmp(replci->keyword, "portaddr") == 0) keep_password = false; } /* Also note whether connstring contains a password. */ @@ -4092,7 +4094,7 @@ do_connect(enum trivalue reuse_previous_specification, * management issues: PQconninfoFree would misbehave on Windows.) * However, to avoid dependencies on the order in which parameters * appear in the array, make a preliminary scan to set - * keep_password and same_host correctly. + * keep_password, same_host and same_port correctly. * * While any change in user, host, or port causes us to ignore the * old connection's password, we don't force that for dbname, @@ -4116,7 +4118,9 @@ do_connect(enum trivalue reuse_previous_specification, } else if (port && strcmp(ci->keyword, "port") == 0) { - if (!(ci->val && strcmp(port, ci->val) == 0)) + if (ci->val && strcmp(port, ci->val) == 0) + same_port = true; + else keep_password = false; } } @@ -4202,6 +4206,16 @@ do_connect(enum trivalue reuse_previous_specification, } else if (port && strcmp(ci->keyword, "port") == 0) values[paramnum++] = port; + else if (((host && !same_host) || (port && !same_port)) && + strcmp(ci->keyword, "portaddr") == 0) + { + /* + * An old portaddr describes where to reach a particular + * server, so drop it if either the host or the port value is + * changing. + */ + values[paramnum++] = NULL; + } /* If !keep_password, we unconditionally drop old password */ else if ((password || !keep_password) && strcmp(ci->keyword, "password") == 0) diff --git a/src/bin/scripts/pg_isready.c b/src/bin/scripts/pg_isready.c index eb8af08c21a..a93eec99742 100644 --- a/src/bin/scripts/pg_isready.c +++ b/src/bin/scripts/pg_isready.c @@ -35,6 +35,7 @@ main(int argc, char **argv) const char *pghost_str = NULL; const char *pghostaddr_str = NULL; const char *pgport_str = NULL; + const char *pgportaddr_str = NULL; #define PARAMS_ARRAY_SIZE 7 @@ -184,6 +185,13 @@ main(int argc, char **argv) else if (def->val) pgport_str = def->val; } + else if (strcmp(def->keyword, "portaddr") == 0) + { + if (opt && opt->val) + pgportaddr_str = opt->val; + else if (def->val) + pgportaddr_str = def->val; + } if (opt) opt++; @@ -195,7 +203,7 @@ main(int argc, char **argv) { printf("%s:%s - ", pghostaddr_str != NULL ? pghostaddr_str : pghost_str, - pgport_str); + pgportaddr_str != NULL ? pgportaddr_str : pgport_str); switch (rv) { diff --git a/src/interfaces/libpq/fe-cancel.c b/src/interfaces/libpq/fe-cancel.c index 4b5945979c4..f9768a9c1c2 100644 --- a/src/interfaces/libpq/fe-cancel.c +++ b/src/interfaces/libpq/fe-cancel.c @@ -156,6 +156,12 @@ PQcancelCreate(PGconn *conn) if (!cancelConn->connhost[0].port) goto oom_error; } + if (originalHost.portaddr) + { + cancelConn->connhost[0].portaddr = strdup(originalHost.portaddr); + if (!cancelConn->connhost[0].portaddr) + goto oom_error; + } if (originalHost.password) { cancelConn->connhost[0].password = strdup(originalHost.password); diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index ee398f13998..18acbeb0795 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -243,6 +243,10 @@ static const internalPQconninfoOption PQconninfoOptions[] = { "Database-Port", "", 6, offsetof(struct pg_conn, pgport)}, + {"portaddr", "PGPORTADDR", NULL, NULL, + "Database-Port-Address", "", 6, + offsetof(struct pg_conn, pgportaddr)}, + {"client_encoding", "PGCLIENTENCODING", NULL, NULL, "Client-Encoding", "", 10, offsetof(struct pg_conn, client_encoding_initial)}, @@ -1403,6 +1407,48 @@ pqConnectOptions2(PGconn *conn) } } + /* + * Next, work out the port number to actually connect to for each host + * name, if portaddr was given. As for port above, these fields may be + * left null or empty; we will use the corresponding port field whenever + * we read such a portaddr field. + */ + if (conn->pgportaddr != NULL && conn->pgportaddr[0] != '\0') + { + int i; + char *s = conn->pgportaddr; + bool more = true; + + for (i = 0; i < conn->nconnhost && more; i++) + { + conn->connhost[i].portaddr = parse_comma_separated_list(&s, &more); + if (conn->connhost[i].portaddr == NULL) + goto oom_error; + } + + /* + * If exactly one portaddr was given, use it for every host. + * Otherwise, there must be exactly as many portaddrs as there were + * hosts. + */ + if (i == 1 && !more) + { + for (i = 1; i < conn->nconnhost; i++) + { + conn->connhost[i].portaddr = strdup(conn->connhost[0].portaddr); + if (conn->connhost[i].portaddr == NULL) + goto oom_error; + } + } + else if (more || i != conn->nconnhost) + { + conn->status = CONNECTION_BAD; + libpq_append_conn_error(conn, "could not match %d portaddr values to %d hosts", + count_comma_separated_elems(conn->pgportaddr), conn->nconnhost); + return false; + } + } + /* * If user name was not given, fetch it. (Most likely, the fetch will * fail, since the only way we get here is if pg_fe_getauthname() failed @@ -1459,7 +1505,10 @@ pqConnectOptions2(PGconn *conn) /* * Try to get a password for this host from file. We use host * for the hostname search key if given, else hostaddr (at - * least one of them is guaranteed nonempty by now). + * least one of them is guaranteed nonempty by now). Likewise, + * the port search key is always port, never portaddr: the + * search keys identify the server we mean to reach, not the + * address we happen to reach it at. */ const char *pwhost = conn->connhost[i].host; const char *password_errmsg = NULL; @@ -2446,7 +2495,9 @@ emitHostIdentityInfo(PGconn *conn, const char *host_addr) displayed_host = conn->connhost[conn->whichhost].hostaddr; else displayed_host = conn->connhost[conn->whichhost].host; - displayed_port = conn->connhost[conn->whichhost].port; + displayed_port = conn->connhost[conn->whichhost].portaddr; + if (displayed_port == NULL || displayed_port[0] == '\0') + displayed_port = conn->connhost[conn->whichhost].port; if (displayed_port == NULL || displayed_port[0] == '\0') displayed_port = DEF_PGPORT_STR; @@ -3067,6 +3118,25 @@ keep_going: /* We will come back to here until there is goto keep_going; } } + + /* + * If portaddr was given, that is the port we actually connect to, and + * port only serves to identify the server, just as host does when + * hostaddr is given. portaddr is ignored for Unix-domain socket + * connections, which are named by port. + */ + if (ch->type != CHT_UNIX_SOCKET && + ch->portaddr != NULL && ch->portaddr[0] != '\0') + { + if (!pqParseIntParam(ch->portaddr, &thisport, conn, "portaddr")) + goto error_return; + + if (thisport < 1 || thisport > 65535) + { + libpq_append_conn_error(conn, "invalid port number: \"%s\"", ch->portaddr); + goto keep_going; + } + } snprintf(portstr, sizeof(portstr), "%d", thisport); /* Use pg_getaddrinfo_all() to resolve the address */ @@ -5108,6 +5178,7 @@ freePGconn(PGconn *conn) free(conn->pghost); free(conn->pghostaddr); free(conn->pgport); + free(conn->pgportaddr); free(conn->connect_timeout); free(conn->pgtcp_user_timeout); free(conn->client_encoding_initial); @@ -5199,6 +5270,7 @@ pqReleaseConnHosts(PGconn *conn) free(conn->connhost[i].host); free(conn->connhost[i].hostaddr); free(conn->connhost[i].port); + free(conn->connhost[i].portaddr); if (conn->connhost[i].password != NULL) { explicit_bzero(conn->connhost[i].password, diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index a737d1db457..f06f418c017 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -361,6 +361,8 @@ typedef struct pg_conn_host char *hostaddr; /* host numeric IP address */ char *port; /* port number (if NULL or empty, use * DEF_PGPORT[_STR]) */ + char *portaddr; /* port number actually connected to, for TCP + * connections (if NULL or empty, use port) */ char *password; /* password for this host, read from the * password file; NULL if not sought or not * found in password file. */ @@ -383,6 +385,10 @@ struct pg_conn * precedence over pghost. */ char *pgport; /* the server's communication port number, or * a comma-separated list of ports */ + char *pgportaddr; /* the port number to connect to, or a + * comma-separated list of same. Takes + * precedence over pgport, except for + * Unix-domain socket connections. */ char *connect_timeout; /* connection timeout (numeric string) */ char *pgtcp_user_timeout; /* tcp user timeout (numeric string) */ char *client_encoding_initial; /* encoding to use */ diff --git a/src/interfaces/libpq/meson.build b/src/interfaces/libpq/meson.build index b0ae72167a1..9087d2972ec 100644 --- a/src/interfaces/libpq/meson.build +++ b/src/interfaces/libpq/meson.build @@ -161,6 +161,7 @@ tests += { 't/004_load_balance_dns.pl', 't/005_negotiate_encryption.pl', 't/006_service.pl', + 't/007_portaddr.pl', ], 'env': { 'with_ssl': ssl_library, diff --git a/src/interfaces/libpq/t/001_uri.pl b/src/interfaces/libpq/t/001_uri.pl index 64f257ae046..613b03e6aec 100644 --- a/src/interfaces/libpq/t/001_uri.pl +++ b/src/interfaces/libpq/t/001_uri.pl @@ -56,6 +56,12 @@ my @tests = ( q{host='example.com' hostaddr='63.1.2.4' (inet)}, q{}, ], + [ + q{postgresql://host:12345/db?portaddr=6000}, + q{dbname='db' host='host' port='12345' portaddr='6000' (inet)}, + q{}, + ], + [ q{postgresql://?portaddr=6000}, q{portaddr='6000' (local)}, q{}, ], [ q{postgresql://%68ost/}, q{host='host' (inet)}, q{}, ], [ q{postgresql://host/db?user=uri-user}, diff --git a/src/interfaces/libpq/t/007_portaddr.pl b/src/interfaces/libpq/t/007_portaddr.pl new file mode 100644 index 00000000000..5ecb573d8a7 --- /dev/null +++ b/src/interfaces/libpq/t/007_portaddr.pl @@ -0,0 +1,166 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# This tests the portaddr connection parameter, which separates the port that +# libpq actually connects to from the port that identifies the server. +# +# portaddr only applies to TCP connections, so the server has to listen on a +# TCP port here, which is why this test is not enabled by default. + +if (!$ENV{PG_TEST_EXTRA} || $ENV{PG_TEST_EXTRA} !~ /\bportaddr\b/) +{ + plan skip_all => + 'Potentially unsafe test portaddr not enabled in PG_TEST_EXTRA'; +} + +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->append_conf('postgresql.conf', "listen_addresses = '127.0.0.1'"); +$node->start; + +# The port the server really listens on, plus a port that nothing listens on. +# Reaching the server while naming the latter is only possible via portaddr. +my $realport = $node->port; +my $unusedport = PostgreSQL::Test::Cluster::get_free_port(); + +# Sanity check: without portaddr, the unused port is unreachable. +$node->connect_fails( + "host=127.0.0.1 port=$unusedport", + "connection to an unused port fails without portaddr", + expected_stderr => + qr/connection to server at "127\.0\.0\.1", port $unusedport failed/); + +# portaddr determines the port we connect to ... +$node->connect_ok( + "host=127.0.0.1 port=$unusedport portaddr=$realport", + "portaddr determines the port connected to", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); + +# ... while port still identifies the connection, as reported by PQport. +$node->connect_ok( + "host=127.0.0.1 port=$unusedport portaddr=$realport", + "PQport reports port, not portaddr", + sql => "\\echo :PORT", + expected_stdout => qr/^$unusedport$/); + +# An empty portaddr means "connect to port", the historical behavior. +$node->connect_ok( + "host=127.0.0.1 port=$realport portaddr=", + "empty portaddr falls back to port", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); + +# A connection failure reports the port we actually tried to reach. +$node->connect_fails( + "host=127.0.0.1 port=$realport portaddr=$unusedport", + "connection failure reports the portaddr port", + expected_stderr => + qr/connection to server at "127\.0\.0\.1", port $unusedport failed/); + +# Invalid values are rejected the same way port is. +$node->connect_fails( + "host=127.0.0.1 port=$realport portaddr=65536", + "portaddr must be a valid port number", + expected_stderr => qr/invalid port number: "65536"/); + +$node->connect_fails( + "host=127.0.0.1 port=$realport portaddr=notanumber", + "portaddr must be an integer", + expected_stderr => + qr/invalid integer value "notanumber" for connection option "portaddr"/); + +# The portaddr list must match the host list, unless it has a single element. +$node->connect_fails( + "host=127.0.0.1,127.0.0.1 port=$unusedport portaddr=$realport,$realport,$realport", + "portaddr list must match the host list", + expected_stderr => qr/could not match 3 portaddr values to 2 hosts/); + +# A single portaddr applies to every host. The first host here is a socket +# path that does not exist, so it fails and the second host is tried; that +# second host can only be reached if the lone portaddr was copied to it. +$node->connect_ok( + "host=/nonexistent,127.0.0.1 port=$unusedport portaddr=$realport", + "a single portaddr applies to all hosts", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); + +# An empty item in the list uses the corresponding port value. The first host +# is directed at the unused port and fails, so the second one is tried, and it +# can only succeed by falling back to its port. +$node->connect_ok( + "host=127.0.0.1,127.0.0.1 port=$unusedport,$realport portaddr=$unusedport,", + "an empty list item falls back to the corresponding port", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); + +# PGPORTADDR behaves the same as the parameter. +{ + local $ENV{PGPORTADDR} = $realport; + + $node->connect_ok( + "host=127.0.0.1 port=$unusedport", + "PGPORTADDR environment variable is honored", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); +} + +# portaddr is ignored for Unix-domain socket connections, which are named by +# port; naming an unused port there must not change anything. +if ($use_unix_sockets) +{ + $node->connect_ok( + $node->connstr('postgres') . " portaddr=$unusedport", + "portaddr is ignored for Unix-domain socket connections", + sql => "SELECT 'connected'", + expected_stdout => qr/^connected$/); +} + +# The password file is searched using port, never portaddr. This is the point +# of the parameter: an entry written for the server's own port keeps matching +# when the connection is made through an intermediary on another port. +$node->safe_psql('postgres', + "CREATE ROLE portaddr_role LOGIN PASSWORD 'secret'"); + +unlink($node->data_dir . '/pg_hba.conf'); +$node->append_conf('pg_hba.conf', "local all all trust"); +$node->append_conf('pg_hba.conf', + "host all portaddr_role 127.0.0.1/32 scram-sha-256"); +$node->append_conf('pg_hba.conf', "host all all 127.0.0.1/32 trust"); +$node->reload; + +my $pgpassfile = "${PostgreSQL::Test::Utils::tmp_check}/pgpass_portaddr"; +$ENV{PGPASSFILE} = $pgpassfile; + +# An entry keyed to the port that identifies the server matches, even though +# the connection is actually made to a different port. +unlink($pgpassfile); +append_to_file($pgpassfile, + "127.0.0.1:$unusedport:postgres:portaddr_role:secret\n"); +chmod 0600, $pgpassfile or die; + +$node->connect_ok( + "host=127.0.0.1 port=$unusedport portaddr=$realport user=portaddr_role", + "password file is searched using port", + sql => "SELECT 'authenticated'", + expected_stdout => qr/^authenticated$/); + +# Conversely, an entry keyed to the port actually connected to does not match. +unlink($pgpassfile); +append_to_file($pgpassfile, + "127.0.0.1:$realport:postgres:portaddr_role:secret\n"); +chmod 0600, $pgpassfile or die; + +$node->connect_fails( + "host=127.0.0.1 port=$unusedport portaddr=$realport user=portaddr_role", + "password file is not searched using portaddr", + expected_stderr => qr/no password supplied/); + +unlink($pgpassfile); +delete $ENV{PGPASSFILE}; + +done_testing(); diff --git a/src/test/perl/PostgreSQL/Test/Utils.pm b/src/test/perl/PostgreSQL/Test/Utils.pm index d3e6abf7a68..0e98a15a9f1 100644 --- a/src/test/perl/PostgreSQL/Test/Utils.pm +++ b/src/test/perl/PostgreSQL/Test/Utils.pm @@ -134,6 +134,7 @@ BEGIN PGKRBSRVNAME PGPASSFILE PGPASSWORD + PGPORTADDR PGREQUIREPEER PGREQUIRESSL PGSERVICE diff --git a/src/test/regress/pg_regress.c b/src/test/regress/pg_regress.c index 21d00f792d2..80cf028ac6e 100644 --- a/src/test/regress/pg_regress.c +++ b/src/test/regress/pg_regress.c @@ -837,6 +837,7 @@ initialize_environment(void) unsetenv("PGKRBSRVNAME"); unsetenv("PGPASSFILE"); unsetenv("PGPASSWORD"); + unsetenv("PGPORTADDR"); unsetenv("PGREQUIREPEER"); unsetenv("PGREQUIRESSL"); unsetenv("PGSERVICE"); @@ -886,6 +887,7 @@ initialize_environment(void) { setenv("PGHOST", hostname, 1); unsetenv("PGHOSTADDR"); + unsetenv("PGPORTADDR"); } if (port != -1) { @@ -893,6 +895,7 @@ initialize_environment(void) snprintf(s, sizeof(s), "%d", port); setenv("PGPORT", s, 1); + unsetenv("PGPORTADDR"); } if (user != NULL) setenv("PGUSER", user, 1); -- 2.43.0
v3-0002-libpq-Add-PQportaddr-and-show-the-port-address-in.patch (text/x-patch, 14.2K) download From 370d2c794694c341049a87c900eb675740fdda24 Mon Sep 17 00:00:00 2001 From: Diego <mrstephenamell@gmail.com> Date: Mon, 27 Jul 2026 14:06:48 -0300 Subject: [PATCH v3 2/2] libpq: Add PQportaddr(), and show the port address in psql \conninfo portaddr lets the port a connection is made to differ from the port that identifies the server, but there was no way to ask libpq which port it actually used. Add PQportaddr(), which reports the port of the current connection just as PQhostaddr() reports its IP address; like that function, it reports nothing for Unix-domain socket connections, which have no port. A LIBPQ_HAS_PORTADDR feature macro is provided, per the convention for new libpq API. Use it in psql's \conninfo, which grows a "Port Address" row displayed only when the port connected to differs from the port identifying the server -- the same rule the existing "Host Address" row follows. No Unix-socket test is needed, or wanted: PQportaddr() is already empty for socket connections, and a TCP connection can exist even with a socket-path host when hostaddr forces it. The \connect success banner likewise reports the port address when it differs, mirroring what commit 6e5f8d489a did for hostaddr. Discussion: https://postgr.es/m/001a6f1d-4adb-42b2-8bf6-44154ed0ab97@gmail.com --- doc/src/sgml/libpq.sgml | 24 ++++++++++ src/bin/psql/command.c | 63 +++++++++++++++++++++++--- src/interfaces/libpq/exports.txt | 1 + src/interfaces/libpq/fe-connect.c | 52 ++++++++++++++++++++- src/interfaces/libpq/libpq-fe.h | 5 ++ src/interfaces/libpq/libpq-int.h | 1 + src/interfaces/libpq/t/007_portaddr.pl | 26 +++++++++++ 7 files changed, 163 insertions(+), 9 deletions(-) diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml index 6b3adb2e449..bf0758372eb 100644 --- a/doc/src/sgml/libpq.sgml +++ b/doc/src/sgml/libpq.sgml @@ -2863,6 +2863,30 @@ char *PQport(const PGconn *conn); </listitem> </varlistentry> + <varlistentry id="libpq-PQportaddr"> + <term><function>PQportaddr</function><indexterm><primary>PQportaddr</primary></indexterm></term> + + <listitem> + <para> + Returns the port that the active connection was actually made to. + This can be the port given by the <literal>port</literal> parameter, + or a port provided through the <literal>portaddr</literal> parameter. +<synopsis> +char *PQportaddr(const PGconn *conn); +</synopsis> + </para> + + <para> + <xref linkend="libpq-PQportaddr"/> returns <symbol>NULL</symbol> if the + <parameter>conn</parameter> argument is <symbol>NULL</symbol>. + Otherwise, if there is an error producing the port information (perhaps + if the connection has not been fully established or there was an + error), or if the connection is made over a Unix-domain socket, it + returns an empty string. + </para> + </listitem> + </varlistentry> + <varlistentry id="libpq-PQtty"> <term><function>PQtty</function><indexterm><primary>PQtty</primary></indexterm></term> diff --git a/src/bin/psql/command.c b/src/bin/psql/command.c index 267c8c7d8b8..66851ed6119 100644 --- a/src/bin/psql/command.c +++ b/src/bin/psql/command.c @@ -794,6 +794,9 @@ exec_command_conninfo(PsqlScanState scan_state, bool active_branch) char *host; bool print_hostaddr; char *hostaddr; + bool print_portaddr; + char *port, + *portaddr; char *protocol_version, *backend_pid; int ssl_in_use, @@ -815,6 +818,8 @@ exec_command_conninfo(PsqlScanState scan_state, bool active_branch) /* Get values for the parameters */ host = PQhost(pset.db); hostaddr = PQhostaddr(pset.db); + port = PQport(pset.db); + portaddr = PQportaddr(pset.db); version_num = PQfullProtocolVersion(pset.db); protocol_version = psprintf("%d.%d", version_num / 10000, version_num % 10000); @@ -827,6 +832,14 @@ exec_command_conninfo(PsqlScanState scan_state, bool active_branch) print_hostaddr = (!is_unixsock_path(host) && hostaddr && *hostaddr && strcmp(host, hostaddr) != 0); + /* + * Likewise for the port actually connected to. No is_unixsock_path() + * test is needed here: PQportaddr() returns an empty string for + * Unix-domain socket connections, and a TCP connection can be made even + * with a socket-path host when hostaddr forces it. + */ + print_portaddr = (portaddr && *portaddr && strcmp(port, portaddr) != 0); + /* Determine the exact number of rows to print */ rows = 12; cols = 2; @@ -834,6 +847,8 @@ exec_command_conninfo(PsqlScanState scan_state, bool active_branch) rows += 6; if (print_hostaddr) rows++; + if (print_portaddr) + rows++; /* Set it all up */ printTableInit(&cont, &pset.popt.topt, _("Connection Information"), cols, rows); @@ -876,7 +891,12 @@ exec_command_conninfo(PsqlScanState scan_state, bool active_branch) /* Server Port */ printTableAddCell(&cont, _("Server Port"), false, false); - printTableAddCell(&cont, PQport(pset.db), false, false); + printTableAddCell(&cont, port, false, false); + if (print_portaddr) + { + printTableAddCell(&cont, _("Port Address"), false, false); + printTableAddCell(&cont, portaddr, false, false); + } /* Options */ printTableAddCell(&cont, _("Options"), false, false); @@ -4350,13 +4370,30 @@ do_connect(enum trivalue reuse_previous_specification, { char *connhost = PQhost(pset.db); char *hostaddr = PQhostaddr(pset.db); + char *portaddr = PQportaddr(pset.db); + bool show_portaddr; + + /* + * Show the port actually connected to when it differs from the + * port that identifies the server. PQportaddr() returns an + * empty string for Unix-domain socket connections, so this + * cannot fire for them. + */ + show_portaddr = (portaddr && *portaddr && + strcmp(PQport(pset.db), portaddr) != 0); if (is_unixsock_path(connhost)) { /* hostaddr overrides connhost */ if (hostaddr && *hostaddr) - printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"), - PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db)); + { + if (show_portaddr) + printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\" (port address \"%s\").\n"), + PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db), portaddr); + else + printf(_("You are now connected to database \"%s\" as user \"%s\" on address \"%s\" at port \"%s\".\n"), + PQdb(pset.db), PQuser(pset.db), hostaddr, PQport(pset.db)); + } else printf(_("You are now connected to database \"%s\" as user \"%s\" via socket in \"%s\" at port \"%s\".\n"), PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db)); @@ -4364,11 +4401,23 @@ do_connect(enum trivalue reuse_previous_specification, else { if (hostaddr && *hostaddr && strcmp(connhost, hostaddr) != 0) - printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"), - PQdb(pset.db), PQuser(pset.db), connhost, hostaddr, PQport(pset.db)); + { + if (show_portaddr) + printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\" (port address \"%s\").\n"), + PQdb(pset.db), PQuser(pset.db), connhost, hostaddr, PQport(pset.db), portaddr); + else + printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" (address \"%s\") at port \"%s\".\n"), + PQdb(pset.db), PQuser(pset.db), connhost, hostaddr, PQport(pset.db)); + } else - printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"), - PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db)); + { + if (show_portaddr) + printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\" (port address \"%s\").\n"), + PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db), portaddr); + else + printf(_("You are now connected to database \"%s\" as user \"%s\" on host \"%s\" at port \"%s\".\n"), + PQdb(pset.db), PQuser(pset.db), connhost, PQport(pset.db)); + } } } else diff --git a/src/interfaces/libpq/exports.txt b/src/interfaces/libpq/exports.txt index 1e3d5bd5867..2ac1198bc00 100644 --- a/src/interfaces/libpq/exports.txt +++ b/src/interfaces/libpq/exports.txt @@ -211,3 +211,4 @@ PQdefaultAuthDataHook 208 PQfullProtocolVersion 209 appendPQExpBufferVA 210 PQgetThreadLock 211 +PQportaddr 212 diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c index 18acbeb0795..b993dc65414 100644 --- a/src/interfaces/libpq/fe-connect.c +++ b/src/interfaces/libpq/fe-connect.c @@ -2462,6 +2462,30 @@ getHostaddr(PGconn *conn, char *host_addr, int host_addr_len) host_addr[0] = '\0'; } +/* ---------- + * getPortaddr - + * Form the port number of the current connection, in the same way that + * getHostaddr() forms its IP address. conn->raddr must be valid. Nothing + * is reported for Unix-domain sockets, which have no port number. + * ---------- + */ +static void +getPortaddr(PGconn *conn, char *port_str, int port_str_len) +{ + struct sockaddr_storage *addr = &conn->raddr.addr; + + if (addr->ss_family == AF_INET || addr->ss_family == AF_INET6) + { + if (pg_getnameinfo_all(addr, conn->raddr.salen, + NULL, 0, + port_str, port_str_len, + NI_NUMERICSERV) != 0) + port_str[0] = '\0'; + } + else + port_str[0] = '\0'; +} + /* * emitHostIdentityInfo - * Speculatively append "connection to server so-and-so failed: " to @@ -3321,6 +3345,7 @@ keep_going: /* We will come back to here until there is */ { char host_addr[NI_MAXHOST]; + char port_str[NI_MAXSERV]; int sock_type; AddrInfo *addr_cur; @@ -3376,8 +3401,8 @@ keep_going: /* We will come back to here until there is goto error_return; /* - * Set connip, too. Note we purposely ignore strdup - * failure; not a big problem if it fails. + * Set connip and connport, too. Note we purposely ignore + * strdup failure; not a big problem if it fails. */ if (conn->connip != NULL) { @@ -3388,6 +3413,15 @@ keep_going: /* We will come back to here until there is if (host_addr[0]) conn->connip = strdup(host_addr); + if (conn->connport != NULL) + { + free(conn->connport); + conn->connport = NULL; + } + getPortaddr(conn, port_str, NI_MAXSERV); + if (port_str[0]) + conn->connport = strdup(port_str); + /* Try to create the socket */ sock_type = SOCK_STREAM; #ifdef SOCK_CLOEXEC @@ -5242,6 +5276,7 @@ freePGconn(PGconn *conn) free(conn->events); pqReleaseConnHosts(conn); free(conn->connip); + free(conn->connport); release_conn_addrinfo(conn); free(conn->scram_client_key_binary); free(conn->scram_server_key_binary); @@ -7742,6 +7777,19 @@ PQport(const PGconn *conn) return DEF_PGPORT_STR; } +char * +PQportaddr(const PGconn *conn) +{ + if (!conn) + return NULL; + + /* Return the port actually connected to */ + if (conn->connhost != NULL && conn->connport != NULL) + return conn->connport; + + return ""; +} + /* * No longer does anything, but the function remains for API backwards * compatibility. diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h index 8ecb9b4a4c7..0389f30a101 100644 --- a/src/interfaces/libpq/libpq-fe.h +++ b/src/interfaces/libpq/libpq-fe.h @@ -69,6 +69,10 @@ extern "C" /* Indicates presence of the PQAUTHDATA_OAUTH_BEARER_TOKEN_V2 authdata hook */ #define LIBPQ_HAS_OAUTH_BEARER_TOKEN_V2 1 +/* Features added in PostgreSQL v20: */ +/* Indicates presence of PQportaddr and the portaddr connection parameter */ +#define LIBPQ_HAS_PORTADDR 1 + /* * Option flags for PQcopyResult */ @@ -415,6 +419,7 @@ extern char *PQpass(const PGconn *conn); extern char *PQhost(const PGconn *conn); extern char *PQhostaddr(const PGconn *conn); extern char *PQport(const PGconn *conn); +extern char *PQportaddr(const PGconn *conn); extern char *PQtty(const PGconn *conn); extern char *PQoptions(const PGconn *conn); extern ConnStatusType PQstatus(const PGconn *conn); diff --git a/src/interfaces/libpq/libpq-int.h b/src/interfaces/libpq/libpq-int.h index f06f418c017..53c8950c221 100644 --- a/src/interfaces/libpq/libpq-int.h +++ b/src/interfaces/libpq/libpq-int.h @@ -490,6 +490,7 @@ struct pg_conn int whichhost; /* host we're currently trying/connected to */ pg_conn_host *connhost; /* details about each named host */ char *connip; /* IP address for current network connection */ + char *connport; /* port number for current network connection */ /* * The pending command queue as a singly-linked list. Head is the command diff --git a/src/interfaces/libpq/t/007_portaddr.pl b/src/interfaces/libpq/t/007_portaddr.pl index 5ecb573d8a7..856101c9541 100644 --- a/src/interfaces/libpq/t/007_portaddr.pl +++ b/src/interfaces/libpq/t/007_portaddr.pl @@ -48,6 +48,32 @@ $node->connect_ok( sql => "\\echo :PORT", expected_stdout => qr/^$unusedport$/); +# PQportaddr() reports the port actually connected to, and psql shows it in +# \conninfo when it differs from the port identifying the server. +my ($ret, $stdout, $stderr) = $node->psql( + 'postgres', + "\\conninfo", + extra_params => ['-w'], + connstr => "host=127.0.0.1 port=$unusedport portaddr=$realport", + on_error_stop => 0); +is($ret, 0, "\\conninfo with portaddr succeeds"); +like($stdout, qr/^Server Port\|$unusedport$/m, + "\\conninfo reports port as the server port"); +like($stdout, qr/^Port Address\|$realport$/m, + "\\conninfo reports portaddr as the port address"); + +($ret, $stdout, $stderr) = $node->psql( + 'postgres', + "\\conninfo", + extra_params => ['-w'], + connstr => "host=127.0.0.1 port=$realport", + on_error_stop => 0); +is($ret, 0, "\\conninfo without portaddr succeeds"); +like($stdout, qr/^Server Port\|$realport$/m, + "\\conninfo without portaddr reports the port"); +unlike($stdout, qr/Port Address/, + "\\conninfo omits the port address when it matches port"); + # An empty portaddr means "connect to port", the historical behavior. $node->connect_ok( "host=127.0.0.1 port=$realport portaddr=", -- 2.43.0
^ permalink raw reply [nested|flat] 11+ messages in thread

* Re: [Proposal] add portaddr like hostaddr
  2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-24 19:23 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
@ 2026-08-26 09:55   ` Denis Smirnov <darthunix@gmail.com>
  2026-08-26 16:25     ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  0 siblings, 1 reply; 11+ messages in thread

From: Denis Smirnov @ 2026-08-26 09:55 UTC (permalink / raw)
  To: Diego <mrstephenamell@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi,

I do not think portaddr should be added to libpq.

Context
-------

The main use case comes from pgcli:

* pgcli opens an SSH tunnel on a random local port;
* it replaces the original database port with that local port;
* the existing .pgpass entry no longer matches;
* portaddr is proposed so that libpq connects to the local port but
  searches .pgpass using the original port.

Why this should not be in libpq
-------------------------------

1. This is a client-side problem.

   The two ports exist only because pgcli created the tunnel. PostgreSQL
   does not know about the local port. A normal libpq connection has one
   host and one port.

2. hostaddr is not a good model for this.

   host and hostaddr are a host name and its numeric network address.
   This distinction is needed for DNS, GSSAPI, and TLS.

   Ports do not have names and addresses. port and portaddr would be two
   different ports with different purposes:

   * port would identify an entry in .pgpass;
   * portaddr would be the port used for the connection.

   This gives a new and unclear meaning to port.

3. The change is much larger than the use case.

   It adds a new libpq parameter, environment variable, public function,
   and special handling in psql, pg_isready, pg_upgrade, and tests.

   Also, the DBeaver example does not show a need in libpq because
   DBeaver uses pgJDBC.

What should happen instead
--------------------------

The client that creates the tunnel should also manage the mapping between:

* the original database endpoint; and
* the local tunnel endpoint.

It should handle the password lookup itself, use a tunnel-specific
passfile, or manage its local ports in another way.

A pgcli implementation detail should not become a new public libpq
connection concept.


Best regards,
Denis Smirnov

^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [Proposal] add portaddr like hostaddr
  2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-24 19:23 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-26 09:55   ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
@ 2026-08-26 16:25     ` Diego <mrstephenamell@gmail.com>
  2026-08-27 03:49       ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  0 siblings, 1 reply; 11+ messages in thread

From: Diego @ 2026-08-26 16:25 UTC (permalink / raw)
  To: Denis Smirnov <darthunix@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

On 2026-08-26 06:55, Denis Smirnov wrote:

Hi Denis!

Thank you for the review.

tl;dr: I think the split is not new: the docs already say that host
identifies the connection in the password file while hostaddr is where
the connection goes. portaddr is the port half of the same split.
Details inline.

 > 1. This is a client-side problem.
 >    The two ports exist only because pgcli created the tunnel. PostgreSQL
 >    does not know about the local port. A normal libpq connection has one
 >    host and one port.

The server never sees the local port, but it never sees host, hostaddr,
passfile or sslmode either: connection parameters are all client-side,
and libpq exists so that every client does not rebuild that half.

Also, the two ports do not only exist when the database client opens
the tunnel. With cloud-sql-proxy, AWS SSM port forwarding, or kubectl
port-forward (":5432" means "pick a random local port"), the mapping
belongs to tooling outside the database client, and the libpq client
behind it is often plain psql, which owns no tunnel at all. There is
no tunnel-creating client there to manage the mapping.

 > 2. hostaddr is not a good model for this.
 >    host and hostaddr are a host name and its numeric network address.
 >    This distinction is needed for DNS, GSSAPI, and TLS.

And for the password file. The current docs, in the hostaddr entry:

     If both host and hostaddr are specified, the value for hostaddr
     gives the server network address. The value for host is ignored
     unless the authentication method requires it, in which case it
     will be used as the host name.
     ...
     Also, when both host and hostaddr are specified, host is used to
     identify the connection in a password file

That last sentence already states the division in question, for the
other coordinate of the same endpoint: one parameter identifies the
entry, the other is where the connection goes. And it is longstanding
behavior, not an accident. As the commit message of e3f99e03e2e puts
it, before v10 libpq "always searched ~/.pgpass using the host
parameter, and nothing else"; when v10 briefly searched by hostaddr
instead, that was fixed as a bug, because it contradicted the
documentation. The lookup key is part of the split's contract.

In code, when both are given, host is not resolved at all, and its
remaining duties are identity duties: the .pgpass search key, the
verify-full certificate check, SNI, the GSSAPI principal. hostaddr
decides one thing: where the socket dials. So the distinction libpq
actually implements is not "a name and its own address"; it is "which
server I mean" and "where I reach it".

 > Ports do not have names and addresses. port and portaddr would be two
 > different ports with different purposes:
 > * port would identify an entry in .pgpass;
 > * portaddr would be the port used for the connection.
 > This gives a new and unclear meaning to port.

I agree that port's identity duties are fewer than host's: no TLS or
GSSAPI role, only the password file plus everything that reports the
connection (psql's prompt, \conninfo, PQport). But the password file
identifies the server by the pair hostname:port, and today only half
of that key can stay logical when the route differs. An endpoint has
two coordinates, host and port; hostaddr split the first, portaddr
completes the second, and there is no third one to creep toward: a
tunnel rewrites exactly these two and nothing else.

And port keeps its meaning under the patch: the server's port, what
the prompt and \conninfo already show. It is the tunnel case today
that forces port into a strange meaning: you must overwrite it with an
ephemeral number that identifies nothing, and every display then
reports that artifact.

 > 3. The change is much larger than the use case.
 >    It adds a new libpq parameter, environment variable, public function,
 >    and special handling in psql, pg_isready, pg_upgrade, and tests.

Of the 585 lines the v3 series adds, 137 are libpq logic; 58% is tests
and documentation (the TAP suite by itself is larger than the core).
That is the usual checklist for a connection option: load_balance_hosts
(7f5b19817ea) added 431 lines of the same shape: parameter, environment
variable, docs, TAP suites, CI.

As for the special handling, all three tools already contain the
hostaddr half of it: pg_isready has printed hostaddr in preference to
host since 2013 (38f43289813), pg_upgrade's check_pghost_envvar
already polices PGHOSTADDR, and psql already shows a Host Address row
and drops a stale hostaddr on \connect. The series fills in the port
column of those existing patterns (44 lines across the three programs
in 0001). For the rest, portaddr follows port's existing list rule
and rides the same surfaces hostaddr already rides (URI, service
file, environment), so the concept cost is the completion of a charge
hostaddr already paid. The public function is in 0002, which, as I
said in the v2 mail, is separable: 0001 stands on its own.

 >    Also, the DBeaver example does not show a need in libpq because
 >    DBeaver uses pgJDBC.

You are right, and I withdraw DBeaver as libpq evidence. What it
still shows is where the trap lives. DBeaver reimplemented the
.pgpass model in its own code, hit exactly this failure
(dbeaver/dbeaver#16499), and fixed it with an option that overrides
the pgpass hostname; its tunnel settings also let the user pin the
local port. Use both and the entry that results is half logical,
half invented: a key for an endpoint that exists nowhere. A client
that needs two workarounds to approximate hostaddr's split is not an
argument against giving the split one shared home. (pgJDBC and
Npgsql reimplement the same file too, with no override at all.)  The
report that shows the need in libpq is pgAdmin, which drives libpq
through psycopg [3].

 > The client that creates the tunnel should also manage the mapping 
between:
 > * the original database endpoint; and
 > * the local tunnel endpoint.
 > It should handle the password lookup itself, use a tunnel-specific
 > passfile, or manage its local ports in another way.

pgAdmin has been doing exactly that, client-side, since at least 2012,
and it shows how far a client can get. The trap was reported inside
pgAdmin development in 2012 [1]. In 2018 the request to make .pgpass
work through pgAdmin's tunnels was rejected as impossible by the
project lead: ".pgpass files cannot be used with SSH tunnelling
because a random port is used for the tunnel, so libpq cannot match
the port number used to one in the pgpass file" [2]. In 2023 pgAdmin
adopted the host + hostaddr split for its tunnels ("Added 'hostaddr'
and used host string as it is while creating SSHTunnel", pgAdmin
commit 81dcc917), so the host half now stays logical for .pgpass and
TLS -- and it still has to hand libpq the ephemeral bind port in
port=, because nothing preserves the port half. The still-open
request for a pinnable local port [3] exists to serve the passfile
lookup, and its reporter also shows what the wildcard workaround
costs: their production and test servers differ only by password, so
host:*:... entries collide under first-match-wins.

pgcli (my fix, dbcli/pgcli#1546) converged on the same point:
preserve the host half through hostaddr, find nothing that preserves
the port half.

On handling the lookup in the client: I wrote that too, for pgcli,
before proposing this. It is a hundred lines plus tests that must
reproduce passwordFromFile's documented behavior (escaping, wildcards,
first match wins, permissions, the localhost rules). A
tunnel-specific passfile needs the same matching logic first, to know
which lines to copy, plus a second file of live passwords to clean up.
Multiply by every tunnel-opening client. A client that does this
correctly has rebuilt the passfile half of libpq and privatized the
split: look up by the coordinates you mean, dial the ones you were
given.

And managing local ports "in another way" means pinning a fixed local
port. Where that is available I already agreed with Christoph: write
the pinned port into .pgpass and you need no patch. But it does not
reach the tunnels above that the database client does not own, nor a
client like a shared pgAdmin server, which multiplexes tunnels for
many users and servers out of one machine's port space. And even
where it works, the passfile entry now keys an invented number that
describes no server.

 > A pgcli implementation detail should not become a new public libpq
 > connection concept.

I see it less as a new concept than as the second half of a split
libpq has documented for host since before v10. pgcli is just where
I hit the port half of it; pgAdmin hit it in 2012.

I will add the patch to the commitfest so it does not get lost, and I
would value your review continuing there. More opinions on the model
question are very welcome. I am not attached to the name -- but I am
attached to the shape: a lookup-only knob (what v1 of this proposal
was) leaves port holding the ephemeral number, so the prompt,
\conninfo and PQport keep reporting an artifact; portaddr keeps port
meaning the server's port for every consumer at once.

[1] 
https://www.postgresql.org/message-id/CANxoLDev2%2BtUi%2BXXyyJZjYrJikRY5aG9eo5qf_Nc%3DrNa0BkzHQ%40ma...
[2] https://github.com/pgadmin-org/pgadmin4/issues/1958
[3] https://github.com/pgadmin-org/pgadmin4/issues/6903

Thank you,
BR,
Diego







^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [Proposal] add portaddr like hostaddr
  2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-24 19:23 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-26 09:55   ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-26 16:25     ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
@ 2026-08-27 03:49       ` Denis Smirnov <darthunix@gmail.com>
  2026-08-27 18:18         ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  0 siblings, 1 reply; 11+ messages in thread

From: Denis Smirnov @ 2026-08-27 03:49 UTC (permalink / raw)
  To: Diego <mrstephenamell@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Diego,

I agree that this is a client-side issue and that libpq is a client
library. But that does not mean libpq should model the whole route to
the server.

A route can contain several SSH hops, proxies, and poolers:

    libpq -> localhost:39907 -> SSH jump1 -> SSH jump2
          -> PgBouncer:6432 -> PostgreSQL:5432

It is not clear why libpq should expose exactly two endpoints. Which
port is the "server port" here: 39907, 6432, or 5432? Only 39907 is
visible to libpq.

I think libpq should keep one connection endpoint, as it does today.
port and PQport() should continue to mean the port to which libpq
actually connects.

SSH forwarding should be configured by SSH itself, for example with
ProxyJump and LocalForward in ~/.ssh/config. If an application creates
a tunnel, it should manage that mapping itself. Pooler routing should
likewise remain in the pooler configuration.

For these reasons, I do not think portaddr belongs in libpq.


Best regards,
Denis Smirnov

^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [Proposal] add portaddr like hostaddr
  2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-24 19:23 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-26 09:55   ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-26 16:25     ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-27 03:49       ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
@ 2026-08-27 18:18         ` Diego <mrstephenamell@gmail.com>
  2026-08-28 04:12           ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-28 15:29           ` Re: [Proposal] add portaddr like hostaddr Jacob Champion <jacob.champion@enterprisedb.com>
  0 siblings, 2 replies; 11+ messages in thread

From: Diego @ 2026-08-27 18:18 UTC (permalink / raw)
  To: Denis Smirnov <darthunix@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

On 2026-08-27 00:49, Denis Smirnov wrote:

Hi Denis!

Thank you, and thank you for conceding the client-side point.

 > It is not clear why libpq should expose exactly two endpoints. Which
 > port is the "server port" here: 39907, 6432, or 5432? Only 39907 is
 > visible to libpq.

The same question, asked about the other coordinate, already has an
answer in libpq.  In your chain:

     libpq -> localhost:39907 -> SSH jump1 -> SSH jump2
           -> PgBouncer:6432 -> PostgreSQL:5432

which one is the host?  Only localhost is visible to libpq, and yet
"host=db.example.com hostaddr=127.0.0.1" is supported, documented, and
used in production today -- pgAdmin does exactly this for its tunnels.
libpq does not model the route there either: hostaddr is the first hop,
the only thing libpq dials, and host is who the user says is at the end
of it.  Everything in between has always been invisible, and nothing in
the patch changes that.

So portaddr adds no knowledge of the route.  It completes the address of
that same first hop.  The patch does not expose two endpoints: it
exposes one endpoint and one identity, which is what host and hostaddr
already are.

And "which port is the server port" is answered the same way as "which
host": by the user, explicitly, or not at all.  If you authenticate
against PgBouncer, the credential is PgBouncer's and port is 6432; if
the tunnel ends at PostgreSQL, it is 5432.  libpq never guesses.  Your
example is in fact where today's workaround breaks: with PgBouncer on
6432 and PostgreSQL on 5432 on one host, the wildcard entry that a
tunnel forces you to write, host:*:..., collapses both into whichever
line comes first.

 > port and PQport() should continue to mean the port to which libpq
 > actually connects.

PQhost() already does not mean the host to which libpq actually
connects: with hostaddr it returns the host verbatim, and PQhostaddr()
returns the address.  Keeping port as the exception is the part that
needs justification.

 > SSH forwarding should be configured by SSH itself, for example with
 > ProxyJump and LocalForward in ~/.ssh/config.

Agreed for the chain itself.  But LocalForward takes an explicit
[bind_address:]port, so that configuration means a fixed local port,
which is exactly the case I already granted Christoph: write it into
.pgpass and you need no patch.  (ProxyJump is not something libpq can
use on its own; libpq calls connect() on a socket and never invokes
ssh.)  What remains is the case where no port can be written in advance,
because it does not exist yet.

I would like to hear other opinions on the model.

Thank you,
BR,
Diego






^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [Proposal] add portaddr like hostaddr
  2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-24 19:23 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-26 09:55   ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-26 16:25     ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-27 03:49       ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-27 18:18         ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
@ 2026-08-28 04:12           ` Denis Smirnov <darthunix@gmail.com>
  1 sibling, 0 replies; 11+ messages in thread

From: Denis Smirnov @ 2026-08-28 04:12 UTC (permalink / raw)
  To: Diego <mrstephenamell@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Diego,

> hostaddr is the first hop, the only thing libpq dials, and host is
> who the user says is at the end of it.

That is not the libpq model.

libpq describes an OS socket endpoint and, when required, a server name.
For TCP, hostaddr is the numeric destination address and port is the
destination port. When hostaddr is absent, host is resolved through DNS.
When both are present, host is retained for TLS and GSSAPI.

host is therefore a name used for address resolution and authentication,
not a general identity at the end of an arbitrary route. Its use as a
.pgpass lookup key does not change that model.

> The patch does not expose two endpoints: it exposes one endpoint and
> one identity.

By two endpoints I meant the two sides of the forwarding mapping created
by pgcli: the local listener and the remote database target.

The socket endpoint used by libpq is already complete:

    127.0.0.1:39907

The remote target:

    db.example.com:5432

belongs to the SSH forwarding configuration owned by pgcli. portaddr
would combine the address from the local endpoint with the port from the
remote endpoint. It does not complete one endpoint.

> What remains is the case where no port can be written in advance,
> because it does not exist yet.

The port exists before pgcli calls libpq. The current pgcli code starts
the SSH tunnel, reads local_bind_ports[0], and then passes that port to
PGExecute. libpq is never asked to connect without a known port.

pgcli creates the tunnel and owns both sides of the mapping. Once the
tunnel is started, pgcli knows the selected local port. It therefore has
all the information needed to construct consistent SSH forwarding and
libpq configuration: SSH maps the local endpoint to the remote database,
while libpq and .pgpass use that local endpoint.

How pgcli stores or generates this mapping is a pgcli implementation
detail. It does not require libpq to introduce a second port.

Best regards,
Denis Smirnov






^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [Proposal] add portaddr like hostaddr
  2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-24 19:23 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-26 09:55   ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-26 16:25     ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-27 03:49       ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-27 18:18         ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
@ 2026-08-28 15:29           ` Jacob Champion <jacob.champion@enterprisedb.com>
  2026-08-28 17:48             ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  1 sibling, 1 reply; 11+ messages in thread

From: Jacob Champion @ 2026-08-28 15:29 UTC (permalink / raw)
  To: Diego <mrstephenamell@gmail.com>; +Cc: Denis Smirnov <darthunix@gmail.com>; pgsql-hackers@lists.postgresql.org

On Thu, Aug 27, 2026 at 11:18 AM Diego <mrstephenamell@gmail.com> wrote:
> I would like to hear other opinions on the model.

I think Denis has this right. You're misinterpreting what host and
hostaddr "mean", in a broader sense, and so the suggested split of
port/portaddr is drawing a parallel where none exists.

Maybe there are good features that would help the UX for a local SSH
tunnel, but I don't get the sense that this is one.

--Jacob





^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [Proposal] add portaddr like hostaddr
  2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-24 19:23 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-26 09:55   ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-26 16:25     ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-27 03:49       ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-27 18:18         ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-28 15:29           ` Re: [Proposal] add portaddr like hostaddr Jacob Champion <jacob.champion@enterprisedb.com>
@ 2026-08-28 17:48             ` Diego <mrstephenamell@gmail.com>
  2026-08-30 05:11               ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  0 siblings, 1 reply; 11+ messages in thread

From: Diego @ 2026-08-28 17:48 UTC (permalink / raw)
  To: Jacob Champion <jacob.champion@enterprisedb.com>; Denis Smirnov <darthunix@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org

Hi Denis / Jacob!

Thank you both for the time you put into this, including reading the
pgcli code.

 > I think Denis has this right. You're misinterpreting what host and
 > hostaddr "mean", in a broader sense, and so the suggested split of
 > port/portaddr is drawing a parallel where none exists.

Point taken. Spelling out what convinced me: when hostaddr is present,
host keeps real name-based duties, TLS server name and certificate
check, GSSAPI principal. The port coordinate has no counterpart for
any of those; the only consumer of a "logical port" would have been the
passfile lookup. That is too little to hang a host/hostaddr-style
split on, so I'm dropping portaddr and withdrawing the CommitFest
entry.

 > Maybe there are good features that would help the UX for a local SSH
 > tunnel, but I don't get the sense that this is one.

May I take you up on that? The residual case is a tunnel on a dynamic
local port: no passfile line can be written in advance, and a client
that wants to keep .pgpass working today has to reimplement the
passfile parser on its side. The first version of this proposal [1]
was a narrowly scoped, lookup-only knob (passfileport): it only changes
the port used in the passfile lookup, and claims nothing about
identity, PQport(), or the socket. Is that a shape worth refining, or
do you see this whole thing as belonging client-side, full stop?

Independently of that, I would like to send a small doc patch for the
pgpass section documenting the workaround that exists today (host +
hostaddr, fixed local port written into .pgpass); the same confusion
keeps resurfacing in client issue trackers.

[1] https://postgr.es/m/c0dfc226-9fbd-450b-a470-00f5427077a4@gmail.com

Thank you,
BR,
Diego






^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [Proposal] add portaddr like hostaddr
  2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-24 19:23 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-26 09:55   ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-26 16:25     ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-27 03:49       ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-27 18:18         ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-28 15:29           ` Re: [Proposal] add portaddr like hostaddr Jacob Champion <jacob.champion@enterprisedb.com>
  2026-08-28 17:48             ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
@ 2026-08-30 05:11               ` Denis Smirnov <darthunix@gmail.com>
  2026-09-04 14:11                 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  0 siblings, 1 reply; 11+ messages in thread

From: Denis Smirnov @ 2026-08-30 05:11 UTC (permalink / raw)
  To: Diego <mrstephenamell@gmail.com>; +Cc: Jacob Champion <jacob.champion@enterprisedb.com>; pgsql-hackers@lists.postgresql.org

Hi Diego,

I think a better solution would be to expose the existing
passwordFromFile() code through a new public libpq API, perhaps
PQpassfileLookup().

Then pgcli could look up the password using the original host and port,
and connect to the local tunnel port with that password. This would avoid
both a new connection parameter and a separate .pgpass parser in each
client.

I would be happy to review such a patch. I think this would be a useful
addition to PostgreSQL.


Best regards,
Denis Smirnov

^ permalink  raw  reply  [nested|flat] 11+ messages in thread

* Re: [Proposal] add portaddr like hostaddr
  2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-24 19:23 ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-26 09:55   ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-26 16:25     ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-27 03:49       ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
  2026-08-27 18:18         ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-28 15:29           ` Re: [Proposal] add portaddr like hostaddr Jacob Champion <jacob.champion@enterprisedb.com>
  2026-08-28 17:48             ` Re: [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
  2026-08-30 05:11               ` Re: [Proposal] add portaddr like hostaddr Denis Smirnov <darthunix@gmail.com>
@ 2026-09-04 14:11                 ` Diego <mrstephenamell@gmail.com>
  0 siblings, 0 replies; 11+ messages in thread

From: Diego @ 2026-09-04 14:11 UTC (permalink / raw)
  To: Denis Smirnov <darthunix@gmail.com>; +Cc: Jacob Champion <jacob.champion@enterprisedb.com>; pgsql-hackers@lists.postgresql.org

Hi Denis,

Done! Patch posted in a new thread:

   [PATCH] libpq: Add PQpassfileLookup()
   https://postgr.es/m/b650e555-11c7-415d-8bda-c747c492ab4a@gmail.com

Thank you again for the suggestion.

BR,
Diego


On 2026-08-30 02:11, Denis Smirnov wrote:
> Hi Diego,
> 
> I think a better solution would be to expose the existing
> passwordFromFile() code through a new public libpq API, perhaps
> PQpassfileLookup().
> 
> Then pgcli could look up the password using the original host and port,
> and connect to the local tunnel port with that password. This would avoid
> both a new connection parameter and a separate .pgpass parser in each
> client.
> 
> I would be happy to review such a patch. I think this would be a useful
> addition to PostgreSQL.
> 
> 
> Best regards,
> Denis Smirnov
> 







^ permalink  raw  reply  [nested|flat] 11+ messages in thread


end of thread, other threads:[~2026-09-04 14:11 UTC | newest]

Thread overview: 11+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-08-13 18:49 [Proposal] add portaddr like hostaddr Diego <mrstephenamell@gmail.com>
2026-08-24 19:23 ` Diego <mrstephenamell@gmail.com>
2026-08-26 09:55   ` Denis Smirnov <darthunix@gmail.com>
2026-08-26 16:25     ` Diego <mrstephenamell@gmail.com>
2026-08-27 03:49       ` Denis Smirnov <darthunix@gmail.com>
2026-08-27 18:18         ` Diego <mrstephenamell@gmail.com>
2026-08-28 04:12           ` Denis Smirnov <darthunix@gmail.com>
2026-08-28 15:29           ` Jacob Champion <jacob.champion@enterprisedb.com>
2026-08-28 17:48             ` Diego <mrstephenamell@gmail.com>
2026-08-30 05:11               ` Denis Smirnov <darthunix@gmail.com>
2026-09-04 14:11                 ` Diego <mrstephenamell@gmail.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox